PDF is blank when downloading using javascript

前端 未结 3 1467
天涯浪人
天涯浪人 2020-12-02 13:20

I have a web service that returns PDF file content in its response. I want to download this as a pdf file when user clicks the link. The javascript code that I have written

3条回答
  •  甜味超标
    2020-12-02 14:20

    I was facing the same problem in my React project. On the API I was using res.download() of express to attach the PDF file in the response. By doing that, I was receiving a string based file. That was the real reason why the file was opening blank or corrupted.

    In my case the solution was to force the responseType to 'blob'. Since I was making the request via axios, I just simply added this attr in the option object:

    axios.get('your_api_url_here', { responseType: 'blob' })
    

    After, to make the download happen, you can do something like this in your 'fetchFile' method:

    const response = await youtServiceHere.fetchFile(id)
    const pdfBlob = new Blob([response.data], { type: "application/pdf" })
    
    const blobUrl = window.URL.createObjectURL(pdfBlob)
    const link = document.createElement('a')
          link.href = blobUrl
          link.setAttribute('download', customNameIfYouWantHere)
          link.click();
          link.remove();
    URL.revokeObjectURL(blobUrl);
    

提交回复
热议问题