Analysis of the stepped pit vue + axios upload files

Upload files is every front-end developer will encounter, before internship to do a file upload function, did not fully do understand the problem, and now re-re footwall.

1. Use formData to upload files, upload files without the use of axios, have done before in school. Generate a target formData

let formData = new FormData()
formData.append('xxx', 'yyyyy')

in input file [0] obtained by dom operation, and then to append formData object online detailed api

Background 2. The method used before after using axios hair before I can not accept the file, the problem is the content-type is application / json, content-type when uploading files used should be multipart / form-data fishes. Read some understanding of the Internet, as if to say this conten-type automatically becomes the multipart / form-data when we upload files, but why is my json it. The key problem in axios body

axios.interceptors.request.use(
  request => {
    store.dispatch('httpStatus', { status: '', statusMsg: '' })
    return request
  },
  error => {
    return Promise.reject(error)
  }
)

axios to our request to make an interception and return to, this time we will be changed to a formData Object, the browser gives the application / json, so our operation failed

3. How to solve this problem?

  3.1 axios we modify the configuration of our action.js in 

let config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }

The results of course not, how could so easily let me get it! ! ! Background error --- NO multipart boundary WAS found, is a two-stage separator system gone, we can add a manual

let config = {
   headers: {
    'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
    } 
}

Can, but I still feel not very good, we should change the headers of the things, Ever since I looked mentor and the online method, posted together.

  3.2 Creating a new axios instance, hung in the prototype vue

  With specific reference to this article https://www.jianshu.com/p/1405f389fb1d

  3.3 My mentor to the program, in action.js, axios third argument config, adding a transformRequest

let config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    transformRequest: [function (data) {
      return data
    }]
  }

About this method I checked the api, he is allowed to say transformRequest before sending to the server, the request to modify the data, this data can be modified callback, after such set config, the problem is solved

 

Guess you like

Origin www.cnblogs.com/czy960731/p/11105166.html