简体   繁体   中英

How to upload an image from the browser using input type as file to the server along with json data using javascript?

After a further research, I see that like superagent library gives you a tool to send an image but the API seems to be requiring the path of the image which is not possible to get from the browser which is my understanding? ie .attach(name, [path], [filename]) so is there a way to solve what I want to achieve using pure JavaScript in npm env starting from selecting an image from the file upload in the browser.

Also my python backend requires a request header to be {content-transfer-encoding: "base64" when the content-type is image/png} and other data to be in JSON format. Anyone who has dealt with npm modules and has a good idea what module to use for this task, please feel free to share your idea.

Thanks for your help!

It took a few hours to get to figure this out. I hope this serves as a guidance for someone who needs to post an image with metadata to the backend server with different content-type in the browser.

export const addBanner = (ctid, token, base64, kwargs) => {
let clientTypeId = ctid;
const URL-ENDPOINT = 'URL-address';
request({method: "POST", 
uri: URL-ENDPOINT, 
withCredentials: false,
multipart: [
  {
  "Content-Disposition": "attachment",
  "Content-Type": "application/json",
  "body" : JSON.stringify({
        key-name1: '',
        key-name2: ''})
  },{
    'Content-Type': "image/png", 
    "content-transfer-encoding": "base64",
    "Content-Disposition": `attachment ; name = ${banner.name}`,
    "body": base64
  }], function(error, response, body){
    if (response.statusCode == 200){
      console.log("sucess")
    }else{
      console.log('error', error, response,body)
    }
   }
 })
}

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