1
votes

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

1
I'm not familiar with react but i'm hoping this answer can help with your issue. please check. stackoverflow.com/questions/44656610/…CodeMonkey
Try giving a.href = url instead of a.href = blobAjmal Noushad
probably, here is the answer: stackoverflow.com/questions/21729451/…Cuong DaoVan

1 Answers

1
votes

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