React axios多个文件上传 [英] React axios multiple files upload

查看:791
本文介绍了React axios多个文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying upload multiple images with axios in React but i cannot figure out what is wrong. First I tried to upload single image and that work just fine. But with multiple images I'm out of options.

我正在像这样创建FormData:

I'm creating FormData like so:

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

axios请求看起来像这样

The axios request looking like this

    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进行上传.签名看起来像这样:

My back-end is written is node/express and I'm using multer for uploading. The signature is look like this:

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

我在PostMan中尝试了此后端端点,并且上传的效果还不错,因此错误必须在前端.感谢您的帮助.

I tried this back-end end point in PostMan and uploading works for just fine, so the error must be on front-end. Thanks for help.

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

UPDATE Right way to pass multiple files in formData:

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

推荐答案

此处是完整的设置(上述答案的扩展版本)

Here is a full working set up (expanded version of the answer above)

客户端:

// 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,节点-mutler)

Server side (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
}

这篇关于React axios多个文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆