Скачать PDF с AJAX GET - PullRequest
       5

Скачать PDF с AJAX GET

0 голосов
/ 07 января 2019

Я могу успешно загрузить CSV-файл через браузер с помощью следующего кода.

выдержка из main.py:

@app.route('/downloadSimulationScore')  
    def download_simulation_score():
    userId = request.args.get('userid')
    download_path = 'data/simulation/'+userId+'/simCombinedOutputForDownload.csv'
    return send_file(download_path,
                 attachment_filename='simulation_score.csv')

отрывок модели.js:

function downloadSimulation(){

$.ajax({
    type: "GET",
    url: server + "/downloadSimulationScore?userid=" +USERID,
    dataType: "text",
    cache: false,
    success: function(data) {
        writeLog("INFO", "Simulation: Downloaded simulation score csv");

        // create file blob
        var binaryData = [];
        binaryData.push(data);
        var blob = new Blob(binaryData, {type:"text/csv"});

        // download file
        if(navigator.msSaveBlob){
            // if IE
            navigator.msSaveBlob(blob, 'simulation_score.csv');
        }
        else {
            var a = document.createElement('a');
            var fileurl = window.URL.createObjectURL(blob);
            a.href = fileurl;
            a.download =  'simulation_score.csv';
            a.click();
        }


        // show alert
        $("#mainAlert").text("CSV file downloaded.")
        $("#mainAlert").addClass('alert--show');

        setTimeout(function(){
            $("#mainAlert").removeClass('alert--show');
        }, 5000);

        // change select back to default
        $("#downloadCSV").val("none")

    },
    error: function(err){
        console.log(err);

        // show alert
        $("#mainAlert").text("No csv data for this day")
        $("#mainAlert").removeClass('alert--success');
        $("#mainAlert").addClass('alert--show');

        setTimeout(function(){
            $("#mainAlert").removeClass('alert--show');
            $("#mainAlert").addClass('alert--success');
        }, 5000);

        // change select back to default
        $("#downloadCSV").val("none");
    }
});
}

Я пытаюсь изменить это так, чтобы я мог скачать PDF вместо CSV. Чтобы добиться этого, я изменил вышеупомянутую функцию следующим образом:

Пересмотренный отрывок sim.js:

// download simulation score
function downloadSimulation(){

$.ajax({
    type: "GET",
    url: server + "/downloadSimulationScore?userid=" +USERID,
    dataType: "text",
    cache: false,
    contentType : 'application/pdf',
    success: function(data) {
        writeLog("INFO", "Simulation: Downloaded simulation report pdf");

        // create file blob
        var binaryData = [];
        binaryData.push(data);
        var blob = new Blob([data], {type:"application/pdf"});

        // download file
        if(navigator.msSaveBlob){
            // if IE
            navigator.msSaveBlob(blob, 'metis_simulation_report.pdf');
        }
        else {
            var a = document.createElement('a');
            var fileurl = window.URL.createObjectURL(blob);
            a.href = fileurl;
            a.download =  'metis_simulation_report.pdf';
            document.body.appendChild(a);
            a.click();
        }


        // show alert
        $("#mainAlert").text("PDF file downloaded.")
        $("#mainAlert").addClass('alert--show');

        setTimeout(function(){
            $("#mainAlert").removeClass('alert--show');
        }, 5000);

        // change select back to default
        $("#downloadCSV").val("none")

    },
    error: function(err){
        console.log(err);

        // show alert
        $("#mainAlert").text("No csv data for this day")
        $("#mainAlert").removeClass('alert--success');
        $("#mainAlert").addClass('alert--show');

        setTimeout(function(){
            $("#mainAlert").removeClass('alert--show');
            $("#mainAlert").addClass('alert--success');
        }, 5000);

        // change select back to default
        $("#downloadCSV").val("none");
    }
});
}

Это загружает пустой PDF в Chrome (без сообщения об ошибке). PDF, загруженный через ie, выдает следующее сообщение об ошибке (в Adobe Acrobat):

Произошла ошибка ввода-вывода файла.

Любая помощь будет оценена.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...