首页 > 解决方案 > 将 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);
        });
    }

标签: javascriptc#postrestsharprest-client

解决方案


我发现了这个问题。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);
        });
    }


推荐阅读