简体   繁体   中英

How can I upload the image file with axios?

Do I need to change the model below to upload images to django restapi ?

function axmethod(url, method, options) {
  if (options !== undefined) {
    var {
      params = {}, data = {}
    } = options
  } else {
    params = data = {}
  }

  return new Promise((resolve, reject) => {
    const config = {

    }
    axios({
      url,
      method,
      params,
      data,

    }).then(res => {
      resolve(res)
    }, res => {
      reject(res)
    })
  })
}

please help if I need to add?

I can see two things that might be the key:

  1. In order to upload a image, you need to specify contentType: "multipart/form-data" in your config object

  2. The uploaded data needs to be a FormData object. Let's say you have an object myCurrentData which contains a name string and the file itself. You can transform it using:

     const data = new FormData(); Object.entries(myCurrentData).forEach(([key, value]) => data.append(key, value || ""));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM