【发布时间】:2021-07-05 10:00:45
【问题描述】:
我在使用 React 和 Express 上传图片时遇到了一些问题,我想知道我是否做错了什么。目前,我正在使用 javascript FileReader 设置我的图像状态,以便在提交表单之前显示要上传的图像的实时预览。我的代码如下所示:
uploadImage = (e) => {
const reader = new FileReader();
reader.onload = (e) => {
if (reader.readyState === 2) {
this.setState({ picture: reader.result });
}
}
reader.readAsDataURL(e.target.files[0])
}
然后,当用户提交表单时,我正在创建一个新的 FormData 对象并将文件附加到它并将其发送到我的后端,如下所示:
createPost() {
// Create form
const data = new FormData();
data.append('file', this.state.picture);
axios.post('/api/createPost', data).then((res) => console.log(res));
}
我的 Express 后端正在使用 multer 来处理文件上传,但某些东西似乎无法正常工作。我使用 diskStorage 设置 multer,然后使用此代码使用此存储实例化一个新的 multer 对象:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __dirname + `/i/posts/${uuid().split('-').join('')}/`)
},
filename: (req, file, cb) => {
console.log(file);
cb(null, Date.now() + path.extname(file.originalname))
}
})
const upload = multer({ storage: storage });
然后,在我的 createPost 路线中,我正在做我从在线教程中找到的内容(这对他们来说没有问题):
app.post('/api/createPost', upload.single('file'), (req, res) => {
// Upload image
console.log(req.file);
})
但是,我没有上传图片,console.log(req.file) 返回未定义。我真的不确定问题出在哪里,因为此时我已经尝试了所有方法,因此请与 stackoverflow 上的所有人联系,希望有人以前曾处理过此问题以寻求帮助。
谢谢!
编辑:
使用Nenad's 的建议我回到使用this.setState({ file: e.target.files[0] }); 为文件设置单独的状态。但是,这并没有解决我的问题,所以我从使用 multer 切换到使用 express-fileupload。然后在我的后端,我能够轻松地处理这些数据并适当地上传文件:
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
const file = req.files.file;
const uploadDir = __dirname + `/i/posts/${uuid().split('-').join('')}/`
// Create new dir
fs.mkdirSync(uploadDir);
// Store upload directory
const uploadPath = uploadDir + Date.now() + '.' + file.name.split('.').pop();
// Store image path for database
const uploadPathArray = uploadPath.split('/')
const imageURL = `/${uploadPathArray.slice(Math.max(uploadPathArray.length - 2)).join('/')}`;
// Use the mv() method to place the file somewhere on your server
file.mv(uploadPath, function(err) {
if (err) return res.status(500).send(err);
// Then push everything into my database
});
如果有人遇到和我一样的 multer 问题,这个解决方案应该会很好用!
【问题讨论】:
标签: reactjs express file-upload multer