Monday 16 December 2019

How to manually upload files from front end to back end

a) Add Content-Type : 'multipart/form-data; charset=utf-8; boundary=' + Math.random().toString().substr(2) to client request (This only works for POST request, GET can not be added)

in Axios, you can use request interceptor
service.interceptors.request.use(
  config => {
      config.headers['Content-Type'] = 'multipart/form-data; charset=utf-8; boundary=' + Math.random().toString().substr(2)
  }
)


b) Create Form data when submitting the request
        // Make form data
        let params = new FormData();
        params.append('name', this.dummy_name);
        // Files
        for (let file of this.my_files) {
            params.append('files[]', file);
        }
        SendPOST(params).then(() => {
   })

https://stackoverflow.com/questions/47630163/axios-post-request-to-send-form-data


Backend caution ~ :
When using multipart/form-data as client request, all form values need to be manually parsed such as using intval(), json_decode(), str_replace('"', '', my_var)

No comments:

Post a Comment