2017-02-27 27 views
0

我需要發送帶有id,名稱和文件(PdfBytes)byte []的數據與ajax到我的服務。在ajax發送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,併發送它在我的服務阿賈克斯。

+0

http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload –

回答

0

我認爲你應該使用選項調用「異步」這樣做的:

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 
    } 
}); 

希望它能幫助。

+0

爲什麼'async:false'有助於發送參數? – Justinas

+0

從什麼不能關聯,以便使用ajax分配變量,這就是爲什麼他得到空 – rad11

1

有兩種方式,在阿賈克斯
發送字節[]你轉換字節[]到字符串GET或JSON的POST =>你應該轉換爲字節數組最主要的文本 和恢復數據格式當致電服務器腳本

$.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" 
}); 

希望它有幫助!