Send byte[] in ajax

I need to send data with id,name , and file (PdfBytes) byte[] with ajax to my service.

How can i add my PDF file to var pdf and add it to my ajax.

My code

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

In the server i get PdfBytes is null

function expect to get byte[] PdfBytes

Sow how i can upload my pdf from my pc to var PdfBytes ,and send it in ajax to my service.

Answers 1

  • There two way to send byte[] in Ajax
    You convert byte[] to string for GET or to json for POST => The main thing you should convert to byte array to text and recover the data format when call the server script

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

    Hope it help!


Related Articles