FormData多个文件上传(fileList集合)

当接口需要文件格式的参数进行文件上传时,前端上传的文件需要使用 FormData

FormData主要作用:网络请求中处理用来异步的上传文件

例如:后端需要前端传的参数file但是他是一个集合List

这里的方式有两种

1.使用jquery的ajax进行上传

2.使用axios进行文件上传

第一种方式实现

js代码

upFiles(formId) {
          const Ajaxurl =this.baseUrl + "/attachment/add?relevanceId=" + formId;
          const _this = this;
          const fileArr = _this.fileList.filter(
            (v) => v.url !== "http://baidu.com"
          );
          // 如果没有新增的附件,就做伪提示
          if (_this.fileList.every((v) => v.url === "http://baidu.com")) {
            _this.$message({ type: "success", message: "上传成功!" });
            _this.saveLoading = false;
            return;
          }
          let formData = new FormData();
          fileArr.forEach((item) => {
            formData.append("file", item);
          });
          $.ajax({
            type: "POST",
            url: Ajaxurl,
            dataType: "json",
        //jquery上传附件的时候需要将下面两个参数设置成false不然会出现报错信息
            processData: false,
            contentType: false,

            beforeSend: function (XMLHttpRequest) {
              XMLHttpRequest.setRequestHeader(
                "binding",
                _this.getCookie("binding")
              );
            },
            data: fd,
            success: function (ajaxResult) {
              _this.tableLoading = false;
              if (ajaxResult.returnCode == 1) {
                _this.$message({
                  type: "success",
                  message: "新增成功",
                });
                _this.loading = false;
                _this.saveLoading = false;
                setTimeout(() => {
                  if (window.opener == null) {
                    window.location.href =
                      "/query.action?id=" + formId + "&m=query";
                  } else {
                    window.opener.location.reload();
                    window.close();
                  }
                }, 1000);
              } else {
                _this.$message({
                  type: "error",
                  message: ajaxResult.returnInfo,
                });
              }
            },
            error: function (err) {
              _this.loading = false;
              _this.saveLoading = false;
              alert("发生错误:" + err.status);
            },
          });
}

tipes:当jquery上传的时候将contentType设置成了formdata的时候出现Uncaught TypeError :Illegal invocation 报错

解决:

 $.ajax中的参数重新进行设置

 processData: false,
 contentType: false,


 $.ajax({
   type: "POST",
   url: Ajaxurl,
   dataType: "json",
   processData: false,
   contentType: false,
   beforeSend: function (XMLHttpRequest) {
      XMLHttpRequest.setRequestHeader("binding", _this.getCookie("binding"));
   },
   data: fd,
   success: function (ajaxResult) {
       成功干什么
   },
   error: function (err) {
       失败干什么
       alert("发生错误:" + err.status);
   }
 })

axios方式实现 

js代码

upFiles(formId) {
        //请求的url
          const Ajaxurl = this.baseUrl + "/attachment/add?relevanceId=" + formId;
          const _this = this;
        //重复文件不再上传
          const fileArr = _this.fileList.filter(
            (v) => v.url !== "http://baidu.com"
          );

          let formData = new FormData();
           //多个文件进行循环添加 formData.append("file", item);多个将会自己转成数组进行上传
          fileArr.forEach((item) => {
            formData.append("file", item);
          });
            
            //请求体
          axios
            .post(Ajaxurl,
              formData, //携带的表单file
              {
                //当时是表单是的时候需要将请求头设置成multipart/form-data
                headers: {
                  "Content-Type":
                    "multipart/form-data; boundary=<calculated when request is sent>",
                  binding: _this.getCookie("binding"),
                },
              }
            )
            .then((ajaxResult) => {
              _this.tableLoading = false;
              if (ajaxResult.data.returnCode == 1) {
                _this.$message({
                  type: "success",
                  message: "新增成功",
                });
                _this.loading = false;
                _this.saveLoading = false;
                return 
                setTimeout(() => {
                  if (window.opener == null) {
                    window.location.href =
                      "/query.action?id=" + formId + "&m=query";
                  } else {
                    window.opener.location.reload();
                    window.close();
                  }
                }, 1000);
              } else {
                _this.$message({
                  type: "error",
                  message: ajaxResult.data.returnInfo,
                });
              }
            })
            .catch((error) => {
              _this.loading = false;
              _this.saveLoading = false;
              alert("发生错误:" + err.status);
            });
        },

 最后看看上传控制台的样子吧

第一种样子

------WebKitFormBoundaryqko4onsawDOCCtSk Content-Disposition: form-data; name="file"; filename="新建文本文档.txt" Content-Type: text/plain   ------WebKitFormBoundaryqko4onsawDOCCtSk--------

------WebKitFormBoundaryk4y2P2fXBa25G7XA1d Content-Disposition: form-data; name="code"

filename="新建文本文档.jpg" Content-Type: multipart/form-data 

------WebKitFormBoundaryk4y2P2fXBa25G7XA1d--

第二种

Node.js中使用FormData可以实现多文件上传。下面是一个简单的示例代码: 首先,需要引入相关的模块: ``` const http = require('http'); const fs = require('fs'); const FormData = require('form-data'); ``` 然后,创建一个FormData对象,用于存储要上传文件: ``` const formData = new FormData(); ``` 接下来,可以通过append方法向FormData对象中添加要上传文件: ``` formData.append('file1', fs.createReadStream('path/to/file1.txt')); formData.append('file2', fs.createReadStream('path/to/file2.txt')); ``` 然后,创建一个请求对象: ``` const options = { hostname: 'localhost', port: 8000, path: '/upload', method: 'POST', headers: formData.getHeaders() }; const req = http.request(options, (res) => { // 处理服务器的响应 }); // 将FormData对象写入请求体 formData.pipe(req); req.on('error', (err) => { console.error(err); }); req.end(); ``` 最后,需要在服务器端接收并处理文件上传的请求。可以使用`multer`模块来处理文件上传: ``` const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.array('file', 2), (req, res) => { console.log(req.files); res.status(200).send('File uploaded successfully'); }); app.listen(8000, () => { console.log('Server started on port 8000'); }); ``` 上面的示例代码为使用Express框架,当有文件上传请求时,会将文件保存到`uploads/`目录下,并打印上传文件信息到控制台。 这就是使用Node.js中的FormData实现多文件上传的简单示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值