【发布时间】:2021-11-03 14:37:13
【问题描述】:
我希望能够直接从开发和生产的前端将图像上传到 ReactJS 公共文件夹。对于生产,我正在使用带有 nodejs 后端的 heroku 应用程序。
从我在网上找到的所有使用 ReactJS 上传图像的教程中,它们都使用服务器端将它们上传到云端,但我想知道是否可以像 Lavarel 那样将它们上传到公共文件夹,是否有这样做有什么缺点吗?
【问题讨论】:
标签: reactjs image file-upload
我希望能够直接从开发和生产的前端将图像上传到 ReactJS 公共文件夹。对于生产,我正在使用带有 nodejs 后端的 heroku 应用程序。
从我在网上找到的所有使用 ReactJS 上传图像的教程中,它们都使用服务器端将它们上传到云端,但我想知道是否可以像 Lavarel 那样将它们上传到公共文件夹,是否有这样做有什么缺点吗?
【问题讨论】:
标签: reactjs image file-upload
我想出了一个解决方案。我找到了一个使用 NodeJS 上传文件的教程。该文件只需要通过端点发送,并在 NodeJS 服务器上像这样处理它。
app.post('/upload', (req, res) => {
if (req.files === null) {
return res.status(400).json({ msg: 'No file uploaded' });
}
const file = req.files.file;
file.mv(`${__dirname}/client/public/uploads/${file.name}`, err => {
if (err) {
console.error(err);
return res.status(500).send(err);
}
res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
});
});
此服务器将图像文件上传到 ReactJS 客户端的 public/uploads 文件夹。然后在响应中返回文件名和文件路径。
【讨论】: