【问题标题】:React axios multiple files uploadReact axios 多文件上传
【发布时间】:2020-02-11 09:15:57
【问题描述】:

我正在尝试在 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)
})

【问题讨论】:

  • 什么是images
  • 图像选择器中的文件数组。
  • 感谢您的回答。我使用的是 FileList 对象而不是 File 对象。但是你的回答让我想到了,谢谢:)

标签: javascript node.js reactjs express axios


【解决方案1】:

这不是生成密钥的正确方法。你可以试试这样:

let productimages = [];

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

【讨论】:

  • 是的,这很好用。我使用的是 FileList 对象而不是 File 对象,这才是真正的问题。谢谢你的回答。
【解决方案2】:

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

客户端:

// 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
}

【讨论】:

  • 什么是客户端的“answerFormData”?它看起来像它的未定义。
  • 在“客户端”的第 3 行...“图像、音频、视频”文件是什么类型的对象?它们是文件路径吗?
  • @lowcrawler 你可以通过var someFile= new File([blob], name + ".extension", { contentType: "some/type" }); 构建它们
  • @UrosRandelovic 谢谢老兄!拯救了我的一天!
猜你喜欢
  • 2021-05-20
  • 1970-01-01
  • 2018-06-21
  • 2017-12-07
  • 2020-12-20
  • 1970-01-01
  • 2023-03-04
  • 2020-10-13
  • 2021-01-05
相关资源
最近更新 更多