【问题标题】:Send byte[] in ajax用ajax发送字节[]
【发布时间】:2017-02-27 07:15:05
【问题描述】:

我需要使用 ajax 向我的服务发送带有 id、name 和文件 (PdfBytes) byte[] 的数据。

如何将我的 PDF 文件添加到 var pdf 并将其添加到我的 ajax。

我的代码

var PdfBytes;
//Tried to fill PdfBytes with get,didnt work
$.get('http://testservices.xxx/PdfService/MYTest.pdf', function(data) 
{
   PdfBytes=data;

});


        var ConvertHtmlToPdfAndSendEmail = {
        "PdfBytes":PdfBytes,
         id": id,
         "Name": name
           };

  $.ajax({
                type: "POST",
                data: JSON.stringify(ConvertHtmlToPdfAndSendEmail),
                dataType: 'json',
                url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload",
                contentType: 'application/json; charset=utf-8',
                async: true,
                cache: false,
                success: function (result) {
                    //my code

                },
                error: function (req, err) {
                   //my code
                }
            })

在服务器中我得到 PdfBytes 为空

函数期望得到byte[] PdfBytes

了解我如何将我的 pdf 从我的电脑上传到 var PdfBytes,并以 ajax 的形式发送到我的服务。

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

在 Ajax 中有两种发送 byte[] 的方法
您将 byte[] 转换为 GET 的字符串或 POST 的 json => 您应该将字节数组转换为文本的主要内容 并在调用服务器脚本时恢复数据格式

$.ajax({
    type: "GET",
    url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload?data="+encodeURI(byte_array.join())
});

$.ajax({
    type: "POST",
    dataType: "json",
    data: JSON.stringify(byte_array),
    url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload"
});

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    我认为你应该使用 option call 'async' 这样做:

    var PdfBytes = $.ajax({
        url: 'http://testservices.xxx/PdfService/MYTest.pdf',
        type: 'GET',
        async: false
    });
    
    var ConvertHtmlToPdfAndSendEmail = {
        PdfBytes: PdfBytes,
        id: id,
        Name: name
    };
    
    $.ajax({
        type: "POST",
        data: JSON.stringify(ConvertHtmlToPdfAndSendEmail),
        dataType: 'json',
        url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload",
        contentType: 'application/json; charset=utf-8',
        async: true,
        cache: false,
        success: function (result) {
            //my code
    
        },
        error: function (req, err) {
            //my code
        }
    });
    

    希望对您有所帮助。

    【讨论】:

    • 为什么要async: false帮助发送参数?
    • 从无法关联的地方使用ajax分配变量,这就是他得到null的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    相关资源
    最近更新 更多