经过进一步研究,我发现像 superagent 库一样为您提供了一个发送图像的工具,但 API 似乎需要图像的路径,而这是不可能从浏览器获取的,这是我的理解?即 .attach(name, [path], [filename]) 那么有没有一种方法可以解决我想要在 npm env 中使用纯 JavaScript 实现的目标,从在浏览器中上传的文件中选择图像开始。
此外,我的 python 后端要求请求 header 为 {content-transfer-encoding: "base64"when the content-type is 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)
}
}
})
}
关于javascript - 如何使用 JavaScript 将输入类型作为文件从浏览器上传图像以及 json 数据到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156946/