2

In React, I uploaded a file using:

        let reader = new FileReader();
        reader.readAsDataURL(file); 
        reader.onloadend = function() {
            let base64data = reader.result;    
            uploadFile(base64data);
            return;
        }

This gives me a Base64 encoded text data:application/octet-stream;base64,JVBERi0xLj... This is fine as when I decode 'JVBERi0xLj...' I get the correct text in case of a text file.

When a download request is made to the server I get the same data back but I'm having a difficulty downloading the file. I receive the same base64 encoded string in the response from the server but unable to open the downloaded file.

I have done the following:

                const blob = new Blob([fetchData], { type: 'application/pdf' })
                let url = window.URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = blob;
                a.download = 'doc.pdf';
                a.click();

Any ideas?

Note: The upload file is converted to base64 to avoid any http communication issues.

Solution following your suggestions:

                let fetchDataModified = `data:application/pdf;base64,${fetchData }`;
                let a = document.createElement("a");
                a.href = fetchData;
                a.download = 'doc.pdf';
                a.click();

When converting to Base64 during upload the data type was set to 'application/octet-stream'. However, when downloading I changed that to 'application/pdf' following Vaibhav's suggestion and used createElement instead of createObjectURL and it worked. Thank you

cleatedheels
  • 67
  • 1
  • 7
  • 1
    I'm not familiar with react but i'm hoping this answer can help with your issue. please check. https://stackoverflow.com/questions/44656610/download-a-string-as-txt-file-in-react – CodeMonkey Jan 20 '21 at 04:20
  • Try giving `a.href = url` instead of `a.href = blob` – Ajmal Noushad Jan 20 '21 at 04:21
  • 1
    probably, here is the answer: https://stackoverflow.com/questions/21729451/pdf-blob-pop-up-window-not-showing-content – Cuong DaoVan Jan 20 '21 at 04:40

1 Answers1

2

“data:application/pdf” + the base64 string that you saved into our database