【问题标题】:Uploading an Image using React and Express使用 React 和 Express 上传图片
【发布时间】: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


    【解决方案1】:

    您的后端代码似乎没问题。但是尝试从前端发送e.target.files[0]。您可以将其存储在某个变量中,然后使用它将formData 附加到createPost() 中。

    const data = new FormData();
    data.append('file', e.target.files[0]);
    

    【讨论】:

    • 感谢您的回复!所以我之前曾尝试使用this.setState({ file: e.target.files[0] }); 将文件存储在一个状态中,然后稍后使用data.append('file', this.state.file); 将其附加到formData,但是当我检查发送到后端的请求时,它总是只是一个空对象。
    • 刚刚在后端的整个请求中达到了一个高峰。似乎该文件是在 request.files.file 中发送的,但是我从未在 multer 中看到过这种情况,因为我看到的每个文档示例都只是 request.file。
    猜你喜欢
    • 2020-11-06
    • 2018-12-16
    • 2020-10-06
    • 2016-06-14
    • 2020-03-22
    • 2011-07-06
    • 2018-11-23
    • 2019-04-05
    • 2017-03-03
    相关资源
    最近更新 更多