javascript - React axios 多文件上传

标签 javascript node.js reactjs express axios

我正在尝试在 React 中使用 axios 上传多个图像,但我无法弄清楚出了什么问题。首先,我尝试上传单个图像,效果很好。但对于多个图像,我别无选择。

我正在创建 FormData,如下所示:

for (let i = 0; i < images.length; i++) {
    formData.append('productPhotos[' + i + ']', images[i]);
}

axios 请求如下所示

    const config = { headers: { 'Content-Type': 'multipart/form-data' } };

    axios
        .post(endPoints.createProduct, formData, config)
        .then(res => console.log(res))
        .catch(err => console.log(err));

我的后端是node/express,我使用multer进行上传。签名如下所示:

app.post("/product", upload.array("productPhotos"), (req, res) => {

我在 PostMan 中尝试了这个后端点,上传效果很好,所以错误一定是在前端。感谢您的帮助。

更新 在 formData 中传递多个文件的正确方法:

images.forEach(img => {
    formData.append("productPhotos", img)
})

最佳答案

这是一个完整的工作设置(上面答案的扩展版本)

客户端:

// silly note but make sure you're constructing files for these (if you're recording audio or video yourself)
// if you send it something other than file it will fail silently with this set-up 
let arrayOfYourFiles=[image, audio, video]
// create formData object
const formData = new FormData();
arrayOfYourFiles.forEach(file=>{
  formData.append("arrayOfFilesName", file);
});

axios({
  method: "POST",
  url: serverUrl + "/multiplefiles",
  data: formData,
  headers: {
    "Content-Type": "multipart/form-data"
  }
})
//some error handling

服务器端(express、 Node - mutler)

const UPLOAD_FILES_DIR = "./uploads";
const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, UPLOAD_FILES_DIR);
  },
// in case you want to change the names of your files)
  filename(req, file = {}, cb) {
    file.mimetype = "audio/webm";
    // console.log(req)
    const {originalname} = file;
    const fileExtension = (originalname.match(/\.+[\S]+$/) || [])[0];
    cb(null, `${file.fieldname}${Date.now()}${fileExtension}`);
  }
});
const upload = multer({storage});

// post route that will be hit by your client (the name of the array has to match)
app.post("/multiplefiles", upload.array('arrayOfFilesName', 5), function (req, res) {
  console.log(req.files, 'files')
  //logs 3 files that have been sent from the client
}

关于javascript - React axios 多文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381990/

相关文章:

javascript - JSON 返回多个同名值

javascript - 如何将 opening_hours.js 包含到 node.js 脚本中?

javascript - 模块中定义的 js 函数可以在模块外部访问吗?

javascript - 在不使用选项卡的情况下浏览 jQuery 对话框中的不同内容

javascript - 从选择框中获取选定的值

node.js - 奇怪的 Create-React-App Heroku 错误 - 无法获取/

javascript - 收到非 bool 属性 Reactjs 的 `true`

javascript - 语法错误: Unexpected token < when trying to test with AVA

node.js - NPM 问题 : Node-pre-gyp. 使用 node-pre-gyp https 下载请求

reactjs - 如何使用 react-router v4 预加载数据?