我有一个React-Express应用程序的问题,名称中带有空格的图像无法在应用程序中呈现,但路径是正确的。没有空格名称的图像可以正常工作。路径是正确的,并且在浏览器中工作,因为使用了%替换空格。
上传图片的组件: ```html
上传图片的组件: ```html
const FileUpload = () => {
const [file, setFile] = useState('');
const [filename, setFilename] = useState('Choose File');
const [uploadedFile, setUploadedFile] = useState({});
const [message, setMessage] = useState('');
const [uploadPercentage, setUploadPercentage] = useState(0);
const onChange = e => {
setFile(e.target.files[0]);
setFilename(e.target.files[0].name);
};
const onSubmit = async e => {
e.preventDefault();
const formData = new FormData();
formData.append('file', file);
try {
const res = await axios.post('/uploads', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
const { fileName, filePath } = res.data;
setUploadedFile({ fileName, filePath });
setMessage('File Uploaded');
} catch (err) {
if (err.response.status === 500) {
setMessage('There was a problem with the server');
} else {
setMessage(err.response.data.msg);
}
}
};
返回:
return (
<Fragment>
<form onSubmit={onSubmit}>
<div className='custom-file mb-4'>
<input
type='file'
className='custom-file-input'
id='customFile'
onChange={onChange}
/>
<label className='custom-file-label' htmlFor='customFile'>
{filename}
</label>
</div>
<input
type='submit'
value='Upload'
/>
</form>
{uploadedFile ? (
<div>
<div>
<h3>{uploadedFile.fileName}</h3>
<img src={uploadedFile.filePath} alt={uploadedFile.fileName} /> // Image here
</div>
</div>
) : null}
</Fragment>
);
};
export default FileUpload;