gpt4 book ai didi

Javascript - 如何将图像数据(字节数组)添加到多部分 POST 请求

转载 作者:行者123 更新时间:2023-11-28 07:50:34 24 4
gpt4 key购买 nike

我正在 Javascript 中构建一个多部分 POST 请求,该请求将使用 AJAX 发送,我需要添加图像作为请求的一部分:

--0xKhTmLbOuNdArY-27f7edea-e541-485f-9bfe-bf9e10b2d6a7
Content-Disposition: form-data; name="uploadedFile"; filename="uploaded-image-a4784b4e-802a-4bed-8fc9-c2a5e038e04f.jpg"
Content-Type: image/jpeg

[Image Data Here]
--0xKhTmLbOuNdArY-27f7edea-e541-485f-9bfe-bf9e10b2d6a7--

我将图像作为字节数组,但直接附加不起作用,我尝试将每个字节转换为其字符代码并将其附加到请求中,但这也不起作用,图像会上传,但是当我检索它时,图像已损坏。

关于如何附加图像数据而不导致版本损坏的任何想法?

最佳答案

一种方法是使用 HTML5 BlobXMLHttpRequest ;像这样:

// Utility to create a random string for multipart boundary
function randomString() {
var str = '';
for (var i = 0; i < 4; i++) {
str += (Math.random().toString(16)+"000000000").substr(2,8);
}
return str;
}

function upload(filename, contentType, byteArray, success, error) {
var file = document.getElementById("file").files[0];
var boundary = randomString();

var blob = new Blob([
"--boundary_" + boundary + "\n"
+ "Content-Type: " + contentType + "\n"
+ "Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"" + filename + "\"\n\n",
byteArray,
"\n\n"
+ "--boundary_" + boundary + "--"
], {type : "multipart/form-data; boundary=\"boundary_" + boundary + "\""});

var request = new XMLHttpRequest();
request.open("POST", url);

request.onreadystatechange = function() {
// if the upload is completed
if (request.readyState == 4) {
// if HTTP status is "Created"
if (request.status == 201) {
// return the response
success(request.response);
} else {
// return the request, which has status, statusText etc
error(request);
}
}
};

request.send(blob);
}

关于Javascript - 如何将图像数据(字节数组)添加到多部分 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26864895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com