为什么上传文件要使用multipart/form-data

最近遇到上传文件的需求:使用了elementui的upload组件:学到了很多知识,这里主要讲讲为什么必须构造表单数据,并使用multipart/form-data content type 请求头。

template:




          
{{!uploadBtnLoading ? "点击上传" : `${successedFileCount}/${uploadFileList.length}个文件`}}
{{langContent.tip}}

js:


uploadFile(option) {

      const formData = new FormData();

      formData.append('controlId', this.node.itemId);

      formData.append('file', option.file);

      formData.append('roleId', this.$refs.role.currentValue);

      this.uploadBtnLoading = true;

      this.combolistNode.configs.frontConfigs.style.disabled = true;

      let cancel;

      const promise = axios

        .request({

          // url: 'http://localhost:9898/m?udp=/udcontrols/udUploadBox/upload',

          url: 'm?udp=/udcontrols/uduploadBox/upload',

          method: 'post',

          data: formData,

          headers: { 'content-type': 'multipart/form-data' },

          cancelToken: new CancelToken(((c) => {

            // An executor function receives a cancel function as a parameter

            cancel = c;

          })),

          onUploadProgress: (progressEvent) => {

            const complete = (progressEvent.loaded / progressEvent.total) * 100;

            option.onProgress({ percent: complete });

          }

        });

      promise.abort = cancel;

      return promise;

    },

multipart/form-data定义源头

multipart/form-data最初由 《RFC 1867: Form-based File Upload in HTML》文档定义。

Since file-upload is a feature that will benefit many applications, this proposes an
extension to HTML to allow information providers to express file upload requests uniformly, and a MIME compatible representation for file upload responses.

文档简介中说明文件上传作为一种常见的需求,在目前(1995年)的html中的form表单格式中还不支持,因此发明了一种兼容此需求的mime type。

The encoding type application/x-www-form-urlencoded is inefficient for sending large quantities of binary data or text containing non-ASCII characters. Thus, a new media type,multipart/form-data, is proposed as a way of efficiently sending the
values associated with a filled-out form from client to server.

文档中也写了为什么要新增一个类型,而不使用旧有的application/x-www-form-urlencoded:因为此类型不适合用于传输大型二进制数据或者包含非ASCII字符的数据。平常我们使用这个类型都是把表单数据使用url编码后传送给后端,二进制文件当然没办法一起编码进去了。所以multipart/form-data就诞生了,专门用于有效的传输文件。

你可能感兴趣的:(为什么上传文件要使用multipart/form-data)