【问题标题】:how can i add multiple images and preview them using react and express?如何添加多个图像并使用 react 和 express 预览它们?
【发布时间】:2019-02-17 18:25:04
【问题描述】:

我正在尝试使用 react 应用添加多个图像并将它们发送到后端代码以将它们存储在 mongodb 中

这是后端的代码: link

这是前端link

所以这段代码只适用于一张图片

我需要能够添加多个图像

【问题讨论】:

    标签: reactjs express


    【解决方案1】:

    服务器

    由于您使用的是multer,请将upload.single() function 更改为upload.array()

    例如:

    app.post("/addItem", 
      upload.array('product-image', 4), // 'product-image' is field name and 4 is the max number of files allowed
      (req, res) => {
        console.log(req.files);
        // ... rest of the logic
      }
    )
    

    查看docs for upload.array()

    客户

    Change current <input> 允许多个文件:

    <input type="file" name="product-image" onChange={this.fileChangeHandler} multiple>
    

    现在保存用户选择的所有图像not only the event.target.files[0]

    fileChangeHandler(event) {
        let files = event.target.files
        this.setState({ selectedFiles: files })
    }
    

    现在add them in FormData 照常上传:

    let formData = new FormData()
    formData.append("product-image", this.state.selectedFiles)
    

    就是这样!希望对您有所帮助。

    PS:我认为不应该将文件添加到状态中。您可以简单地将它们添加到类变量中。在this answer 中,我解释了为什么以及如何做到这一点。


    更新:

    您现在需要遍历文件。您的/addItem 端点的代码将如下所示:

    app.post("/addItem", upload.array('product-image', 4), (req, res) => {
      console.log(req.files);
    
      let paths = [];
    
      req.files.forEach(file => {
        console.log("new file location", file.path)
    
        let extension = file.originalname.split(".").pop()
        fs.rename(file.path, file.path + "." + extension, () => {})
        paths.push("/" + file.filename + "." + extension);
      });
    
      console.log("body", req.body)
    
      let itemToStore = {
        paths: paths,  // notice this `paths` now, it was `path`
        description: req.body.description
      }
    
      console.log("we are adding", itemToStore)
      itemData.push(itemToStore)
      console.log("updated itemData:", itemData)
      res.send(JSON.stringify(itemData))
    })
    

    我没有修改您的代码,只是添加了一个循环。您的 'path' of undefined 错误应该会消失。

    【讨论】:

    • 我试图这样做,但它不起作用服务器中的错误,即路径未定义。你能试试,然后把结果发给我吗?当我上传文件时,它会显示我上传的文件数量,因此未定义路径。 @mehamasum
    • 请分享完整的堆栈跟踪。
    • 我想我猜到了错误。您现在应该遍历文件以保存它们。看看我更新的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2012-12-08
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    相关资源
    最近更新 更多