Скачать PDF-файл из в javascript AJAX вызова - PullRequest
0 голосов
/ 23 декабря 2019

Я пытаюсь загрузить pdf-файл из ответа API, API возвращает файл в виде вложения,

def function():
    file = ReportFileHandler.read_file(current_doc.name)
    file_data = file['Body'].read()
    response = make_response(file_data)
    response.headers['Content-Type'] = file['ContentType']
    response.headers['Content-Disposition'] = "attachment;filename=%s" % current_doc.name
    response.headers['Access-Control-Expose-Headers'] = 'Content-Disposition'
    return response

в коде js, который я пытаюсь ниже


  base64ToArrayBuffer(data) {

    var binaryLen = data.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = data.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
  },

  async model(){
      const apiService = this.get('apiService');
      try{
        let response = await apiService.get(`report/${81}/document/${14}/?format=pdf`);
        var arrBuffer = base64ToArrayBuffer(response);
        var newBlob = new Blob(arrBuffer, {type: "application/pdf"})

        // IE doesn't allow using a blob object directly as link href
        // instead it is necessary to use msSaveOrOpenBlob
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(newBlob);
          return;
        }

        // For other browsers:
        // Create a link pointing to the ObjectURL containing the blob.
        const data = window.URL.createObjectURL(newBlob);
        var link = document.createElement('a');
        link.href = data;
        link.download="file.pdf";
        link.click();
        console.log(response);
      }catch(error){
        console.log(error);
      }
  },

, но этозагружает пустой файл PDF или иногда выдает ошибку в загрузке PDF.

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