Recently, the product raised a requirement to input data in batches according to Excel files. I was the first time to do file import, so reference the old code to find out.

The Content-Type of the unified Request tool

The content-Type is written as Application/X-protobuf because the system platform has not done file import before. In this case, an error is reported, and my backend interface returns the following error (here the backend is set, but there may be other cases).

You can see the request header in the control panel as shown below:

This will change the request tool.

The content-type changes

At present, it is necessary to judge and identify the Content-Type. Make the Content-Type change to multipart/form-data when passed in Excel.

Previous requests were passed to the tool {url: XXXXX,data,method: ‘POST’}, and each request automatically assigned a value to the Content-Type. {url: XXXXX,body,method: ‘POST’}} now change the Excel request, separate from the other requests, change the data,body, easy to make a decision. If the body in the options object exists, it is not mandatory to set the content-Type.

let headers2 = ' '
  if (options.body) {
    headers2 =  tokenRequired ? {
        ...{
          'Authorization': util.cookies.get('token')
        },
        ...headers
      } : {
        ...headers
      }
  } else {
    headers2 =  tokenRequired ? {
      ...{
        'Content-Type': 'application/x-protobuf'.'Authorization': xxxxxx }, ... headers } : { ... {'Content-Type': 'application/x-protobuf',},... headers } }Copy the code

New FormData() automatically takes content-Type

With the FormData() constructor, the browser automatically recognizes and adds the request header “Content-Type: multipart/form-data”, and the parameters still look like key-value pairs for form submission.

let uploadFormData = new FormData();
uploadFormData.append("file", file);
uploadFormData.append("fileName", "file");
this.uploadAry.push(uploadFormData);
Copy the code

The file parameter is read from a file to an object, read by the component < el-upload > property :before-upload=”beforeUpload”. this.uploadAryParameters are the parameters when the interface is requested. Request the interface separately, based on the array element.

this.uploadAry.forEach(async (res) => {
          // console.log('>>>>>>>>>>res',res);
          await productImport(res).then((suc) => {
            if (suc.errorMsg == "Success") {
            }
          });
        });
Copy the code

The final result

Request headers are automatically wrappedContent-Type: multipart/form-data

The file is parsed as follows: