0

I have an html form which i parse to json and send it to my java- backend.

        var data = {};
        var formArray = $("#form").serializeArray();
        $.each(formArray, function (i, field) {
            if(field.name !== '') {
                data[field.name] = field.value;
            }
        });

        $.ajax({
            type: "POST",
            url: encodedContextPath + "/form/send",
            data: JSON.stringify(data),
            dataType: "json",
            contentType: 'application/json'
            ........

Now i need to add the ability to also upload a pdf file, how can i put this file into my json which i'll send to the backend? Can i serialize it somehow or generate a data stream which i can put into the json?

pr191ex
  • 88
  • 1
  • 14
  • Possible duplicate of [pdf file upload ajax html](https://stackoverflow.com/questions/28207106/pdf-file-upload-ajax-html) – messerbill Jan 31 '19 at 17:54

1 Answers1

0

You can use FileReader to get the data of pdf file and send it in json.

let pdfFile;
$('<file-input-id-or-class>').on('change', onPdfUpload);

function onPdfUpload($event) {
    let file = $event.target.files[0];
    if (!file) return;

    let reader = new FileReader();
    reader.onload = function (e) {
        pdfFile = reader.result;
    };
    reader.readAsDataURL(file);
}


var data = {};
    var formArray = $("#form").serializeArray();
    $.each(formArray, function (i, field) {
        if(field.name !== '') {
            data[field.name] = field.value;
        }
    });

   data.pdfFileContent = pdfFile;// you can change field name accordingly

    $.ajax({
        type: "POST",
        url: encodedContextPath + "/form/send",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: 'application/json'
Rakesh Makluri
  • 647
  • 4
  • 10
  • I managed to send the file to my backend but now im struggling getting back the data from the base64 String – pr191ex Feb 01 '19 at 15:21
  • For displaying PDF from Base64, you can check this: https://stackoverflow.com/questions/40674532/how-to-display-base64-encoded-pdf – Rakesh Makluri Feb 04 '19 at 05:50