javascript - 将 RestSharp Reqest AddParameter 转换为 POST 请求的 JavaScript 数据
问题描述
有谁知道什么是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);
});
}
解决方案
我发现了这个问题。Fiddler 帮助调查发送的内容。默认情况下,传入的数据正在被序列化。为了防止这种情况,我们需要明确告诉不要序列化它。"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);
});
}
推荐阅读
- javascript - 如何在 npm install 中克服这个错误?
- python - 如何在多个打印命令之间随机选择?
- python - 重做在 Windows 上无法为 Tkinter 文本小部件工作
- ruby - 为什么你可以在函数中使用另一种方法而不是赋值运算符来更改 Ruby 中局部变量的值?
- python - 如何读取 brat annotation toll 提供的 ann 文件并将它们转换为 python 中的数据框?
- python - 是否可以在 Python Wand(绘图标题)中使用多种字体?
- python - 将信号转发给使用 Popen 创建的子进程
- javascript - reactjs在地图功能内切换启用/禁用按钮
- java - 我在 JavaFX 应用程序中收到 java.lang.reflect.InvocationTargetException 异常,我不知道如何修复它
- typescript - 用 Jest 测试 vue 组件似乎没有使用我的模拟商店吸气剂