如何使用输入类型作为文件从浏览器上载图像到服务器以及使用javascript的json数据

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

本文关键字:服务器 javascript 数据 json 图像 类型 输入 何使用 文件 上载 浏览器      更新时间:2023-09-26

经过进一步的研究,我看到像超级代理库给你一个工具来发送图像,但API似乎需要图像的路径,这是不可能从浏览器这是我的理解?即.attach(name, [path], [filename]),那么是否有一种方法可以解决我想要在npm环境中使用纯JavaScript实现的目标,从从浏览器中上传的文件中选择图像开始。

我的python后端也需要一个请求头是{content-transfer-encoding: "base64"当内容类型是image/png}和其他数据是JSON格式。任何使用过npm模块的人,如果你知道该使用哪个模块来完成这个任务,请随时分享你的想法。

谢谢你的帮助!

我花了几个小时才弄明白。我希望这可以为需要将带有元数据的图像发布到浏览器中具有不同内容类型的后端服务器的人提供指导。

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)
    }
   }
 })
}