gpt4 book ai didi

javascript - 我需要在 Chrome 中上传一个文件,并且需要在同一个请求中**发布**一些参数

转载 作者:行者123 更新时间:2023-11-28 03:53:48 25 4
gpt4 key购买 nike

我需要在 Chrome 中上传一个文件,并且需要在同一请求中发布一些参数,并且需要基本身份验证。我想使用 javascript AJAX 来做到这一点。但是 chrome 不支持 sendAsBinary,我该怎么做?

function sendMsg(status){

var user = localStorage.getObject(CURRENT_USER_KEY);
var file = $("#imageFile")[0].files[0];

var boundary = '----multipartformboundary' + (new Date).getTime();
var dashdash = '--';
var crlf = '\r\n';

/* Build RFC2388 string. */
var builder = '';

builder += dashdash;
builder += boundary;
builder += crlf;

var xhr = new XMLHttpRequest();
var upload = xhr.upload;
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
//
}
};

  if(upload){
upload.onprogress = function(ev){
onprogress(ev);
};
}

/* Generate headers. [STATUS] */
builder += 'Content-Disposition: form-data; name="status"';
builder += crlf;
builder += crlf;

/* Append form data. */
builder += msg;
builder += crlf;

/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;

/* Generate headers. [PIC] */
builder += 'Content-Disposition: form-data; name="pic"';
if (file.fileName) {
builder += '; filename="' + file.fileName + '"';
}
builder += crlf;

builder += 'Content-Type: '+file.type;
builder += crlf;
builder += crlf;

/* Append binary data. */
builder += file.getAsBinary(); //chrome do not support getAsBinary()
builder += crlf;

/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;

/* Mark end of the request. */
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;

xhr.open("POST", apiUrl.sina.upload, true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Authorization', make_base_auth_header(user.userName, user.password));
xhr.sendAsBinary(builder); //chrome do not support sendAsBinary()

xhr.onload = function(event) {
/* If we got an error display it. */
if (xhr.responseText) {
console.log(xhr.responseText);
}
};
};

最佳答案

使用xhr.send(FormData)。您不需要自己构造 multipart-form-data :)在这里查看我的回复:

Javascript/HTML5 file API reading sequential files into multipart form data

关于javascript - 我需要在 Chrome 中上传一个文件,并且需要在同一个请求中**发布**一些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3281842/

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