0

So I am retrieving a file from backend. I want to convert the file back to .xlsx format from Base64 and download said file. However, after downloading the file and opening it, it gives the error "Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

Like This I am saving the file using filesaverjs.

The file is encoded like this:

data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,UEsDBBQABgAIA...

Here's my code:

function convertToFile(file){
    var arr = file.FILE_ENCODE.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = Buffer.from(arr[1]).toString('binary'),
    n = bstr.length,
    u8arr = new Uint8Array(n);
    while(n--){
    u8arr[n] = bstr.charCodeAt(n);
    }
    saveAs(new File([u8arr], "test.xlsx", {type:mime}))
}

Not sure exactly what I am doing wrong so any help would be immensely appreciated.

  • you're not decoding the base64 string. Actually the result of all the code starting from `bstr = Buffer...` to `saveAs.(..` is a xlsx file that contains the original Base64string `UEsDBBQABgAIA...` again, because you just convert every character in the string to byte and write these bytes to a file, which will then contain the same bytes as the original data. Please read more about [base64 encoding](https://en.wikipedia.org/wiki/Base64) – jps Feb 24 '22 at 11:59

0 Answers0