卷曲
正如你可以在curl manpage阅读,这种形式上传通过指定的数据串完成的,可以直接从一个文件--data-binary @/path/to/file
语法完成:
--data-binary <data>
(HTTP) This posts data exactly as specified with no extra processing whatsoever.
If you start the data with the letter @, the rest should be a filename. Data is
posted in a similar manner as --data-ascii does, except that newlines and car‐
riage returns are preserved and conversions are never done.
If this option is used several times, the ones following the first will append
data as described in -d, --data.
如果图像只能以您的语言中的二进制字符串形式提供,例如作为Node.js缓冲区,并且您不希望击中文件系统,那么您可能必须通过将其包含在'
字符中并将其替换为每个'
字符与适当的转义序列的字符串如'\''
或如果这让你不安,'"'"'
。 (回想一下,echo 'abc'"def"'ghi'
回音必abcdefghi
为一个单元。)
Node.js的
节点是多一点宽容,因为它有一个明确的缓冲类型,但它确实需要多一点建设,使其工作。在这里,我将回复数据封装在Promise中以备需要时使用:
const http = require("http");
function upload(image_buffer, image_id) {
return new Promise((accept, reject) => {
let options = {
method: "PUT",
hostname: "maven.nabisco.com",
port: 80,
path: "/artifactory/cdt-repo/folder/" + image_id,
headers: {
"Content-Type": "application/octet-stream",
"Content-Length": image_buffer.length
}
};
let data = [];
let request = http.request(options, response => {
response.on("data", chunk => data.push(chunk));
response.on("end",() =>
accept({
headers: response.headers,
statusCode: response.statusCode,
data: Buffer.concat(data)
})
);
});
request.on("error", err => reject(err));
request.write(image_buffer);
request.end();
});
}
[JSON字符串中的二进制数据可能重复。比Base64更好的东西](https://stackoverflow.com/questions/1443158/binary-data-in-json-string-something-better-than-base64)。查看@Ælex的答案。 – cybersam
不,我不想把二进制数据放在JSON中,我正在寻找在请求中写入二进制文件,并完全避免JSON –