FormData transfers multiple files and other data simultaneously

Recently, there is a requirement: In the web dialog box, users can input text content and upload attachments. The number of attachments is not limited, and the total size of all attachments does not exceed 20M.

There are more than one way to achieve this. For example, the previous back-end colleagues required that the file and text be transmitted separately. The file is uploaded with a separate interface. After the upload is successful, an id is returned, and the id and the text are passed together in another interface. The backend is fine, and the backend will find the corresponding file according to the id. This implementation is relatively simple. Many upload components (such as UI components such as elemenUI plus, arco-design, and ant design) can support uploading files .

However, what the back-end colleagues of this cooperation require is an interface, and files and texts are transmitted to the back-end with FormData.

What is FormData?

Introduction to FormData in MDN
: The FormData interface provides a key/value construction method representing form data, and can easily send the data through the XMLHttpRequest.send() method. This interface is equivalent to this method. Simple and straightforward. If the sending encoding type is set to "multipart/form-data", it will use the same format as the form.
If you want to construct a simple GET request with query parameters in the passed form, you can pass it directly to URLSearchParams.
Objects that implement the FormData interface can be used directly in the for…of structure without calling entries(): for (var p of myFormData) is the same as for (var p of myFormData.entries()).

FormData constructor FormData():

 new FormData();
 FormData.append()   // 向 FormData 中添加新的属性值

Next look at the implementation:


//  upload 组件获取文件列表就不写了,暂定这里获得 文件列表 fileList: [ ]
const allFileMaxListSize = 20971520, // 所有上传文件的大小 20M(20*1024*1024)
const fileFormData = new FormData();
let totalFileSize = 0;
// 这里我用的是 forEach 循环 append 添加,也可以不用 forEach 自己说手动 多次 append,根据自己的需求
fileList?.forEach((item: any) => {
   fileFormData.append('files', item.file); 
    totalFileSize += item.file.size;
  });
  
// 注释!!!!这里为什么可以循环给 fileFormData.append('files', item.file); 因为 向 FormData 中添加新的属性值,FormData 对应的属性值存在也不会覆盖原值,而是新增一个值,如果属性不存在则新增一项属性值。

if (totalFileSize > data.allFileMaxListSize) {
        alert('上传文件总和超过20M!');
      } else {
        const value = `${这里是文本的数据}`;
        fileFormData.append('txt', value);
        fileFormData.append('id', current);  // 如果当前修改数据的id,这行可有可无看具体情况
        try {
          commitComment(String(ticketId), fileFormData);  // 发送请求
         fileList = [];  // 清空
          alert('提交成功!');
        } catch {
          alert('error');
        }
      }

So the core key is this sentence:

Image screenshot mdn

Hope this article helps you!

Guess you like

Origin blog.csdn.net/JaneLittle/article/details/129307141