任何人都知道restsharp的等同:
request.AddParameter("text/plain", body, ParameterType.RequestBody);
在JavaScript中?那是我缺少的唯一部分。
这是C#中的工作代码:
public static void UploadFile(string bearer)
{
var client = new RestClient("...");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + bearer);
request.AddHeader("cache-control", "no-cache");
var imageLenngth = new FileInfo(@"...").Length;
request.AddHeader("Content-Type", "image/jpeg");
request.AddHeader("Content-Length", imageLenngth.ToString());
byte[] body = File.ReadAllBytes(@"...");
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
}
且未在Ajax JavaScript中进行完全工作的代码(它上传到云服务器,但错误地上传图像。将损坏的映像插入了损坏的图像,它应该应该使用太多的字节):
function uploadingImage(binaryImage) {
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "image/jpeg",
"Authorization": "Bearer ...",
"cache-control": "no-cache",
},
"data": binaryImage
}
$.ajax(settings).done(function (response) {
console.log(response);
});
}
我找到了问题。提德勒帮助调查了正在发送的内容。默认情况下,传递的数据正在序列化。为了防止这种情况,我们需要明确说明不要序列化。" processData":false做到了。这是工作代码:
function uploadingImage(binaryImage) {
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "image/jpeg",
"Authorization": "Bearer ...",
"cache-control": "no-cache",
},
"processData":false,
"data": binaryImage
}
$.ajax(settings).done(function (response) {
console.log(response);
});
}