通过Jquery Ajax发送二进制数据

时间:2019-07-10 12:16:05

标签: javascript jquery ajax webkit

我想使用jquery ajax将二进制发布数据发送到服务器后端,但我无法成功。

这样的成功发布数据

Success Result

Success result source

我正在使用这样的代码

    var newBoundary = createRandom(16)
var datax  = '------WebKitFormBoundary'+ newBoundary +'\n'
    datax += 'Content-Disposition: form-data; name="queryOptionsDTO"; filename="blob"\n'
    datax += 'Content-Type: application/json\n\n'

    datax += '{"queryPage":{"initialPage":0,"pageSize":15},"sortInfo":{"sortFields":[{"propertyName":"updateDate","ascending":false}]},"queryParameterDTOs":[{"queryParameterType":"SIMILARITY","propertyName":"kurum.gorunenAd","similarityStrategy":"START"},{"queryParameterType":"SIMILARITY","propertyName":"markaAdi","similarityStrategy":"START"},{"queryParameterType":"EQUALITY","propertyName":"barkodNumarasi","value":"'+ barkod +'"},{"queryParameterType":"SIMILARITY","propertyName":"piyasayaArzIsmi","similarityStrategy":"START"},{"queryParameterType":"SIMILARITY","propertyName":"urunCinsi","similarityStrategy":"START"},{"queryParameterType":"CONTEXT","propertyName":"menseiUlkeAdi","similarityStrategy":"START"},{"queryParameterType":"EQUALITY","propertyName":"ucYasAltiCocuklarIcinUretilmis"},{"queryParameterType":"EQUALITY","propertyName":"ithalImalBilgisi"}],"queryTotal":false}\n'

    $.ajax({
     beforeSend: function(xhrObj){
            xhrObj.setRequestHeader("anonymousUtsToken",sessionStorage.getItem("anonymousUtsToken"));
            xhrObj.setRequestHeader("preferredLocale","tr-TR");
            xhrObj.setRequestHeader("Accept","application/json, text/plain, */*");
            xhrObj.setRequestHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundary"+ newBoundary);
    },
        url: '/UTS/vat/rest/vatKozmetik/kozmetikUrunSorgula',
        type:"POST",
        dataType:"binary",
        data: datax,
        processData:false,
        contentType:false,
        success:function (data, status, req) {
            console.log( req);
        },
        error:function (req, status, error) {
            console.log(req);
        }
    });

但是这样的结果 enter image description here

我该如何发送数据;  queryOptionsDTO :(二进制)

1 个答案:

答案 0 :(得分:0)

您可以使用FileReader对象读取文件的内容:

var fileReader = new FileReader();
fileReader.addEventListener('load', function () {
   var result = fileReader.result;
   $hidden.val(result);
});
fileReader.readAsDataURL(file);

FileReader对象异步读取文件,并在完成时触发回调。这样,您就可以通过从文件阅读器中发布结果(基本64字符串)来获取文件的内容并将其发送到AJAX。

改编自我的original blog post

还有Uploadify之类的其他插件可以提供此功能。