Keywords: JavaScript | download file | Blob | ArrayBuffer | base64
Abstract: This article addresses the common issue of downloading corrupted files from byte arrays in JavaScript. By explaining that Blob requires array buffers, it provides a solution through converting base64 to Uint8Array, with code examples to ensure proper file download. The detailed analysis covers problem root causes, conversion methods, and implementation steps, suitable for frontend developers.
Introduction
In web development, downloading files from AJAX responses is a common task. However, when the response contains bytes, such as in base64 format, directly creating a Blob can lead to corrupted files. This article explores how to overcome this issue through proper data conversion.
Problem Analysis
The issue arises because the Blob constructor expects an array of ArrayBuffer objects or typed arrays like Uint8Array. If raw bytes are provided without proper conversion, the file may become corrupted due to incorrect data formatting. For instance, when obtaining base64-encoded bytes from a server, it must first be decoded to binary bytes.
Solution: Converting Base64 to Array Buffer
To correctly handle base64-encoded data, it must first be converted to an array buffer. The function base64ToArrayBuffer demonstrates this conversion by decoding the base64 string to binary and storing it in a Uint8Array. The complete function implementation is as follows:
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}This function uses window.atob to decode the base64 string, then converts each character to its corresponding ASCII code and stores it in the Uint8Array.
Implementing File Download
Once the array buffer is obtained, it can be used to create a Blob and trigger the download. The function saveByteArray encapsulates this process by creating a link element to download the file. The code is as follows:
function saveByteArray(reportName, byte) {
var blob = new Blob([byte], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = reportName;
link.click();
};This function creates a Blob object with the given type (e.g., "application/pdf"), generates a URL and sets it as the link's href property. By setting the download property to specify the filename and calling the click method, it simulates a user click for download.
Code Integration
To use these functions, first convert the base64 data to an array buffer, then save it as a file. Example usage:
var sampleArr = base64ToArrayBuffer(data);
saveByteArray("Sample Report", sampleArr);In practical applications, the functions can be adjusted based on needs, such as changing file types or handling other data formats.
Conclusion
By ensuring proper conversion of base64 bytes to array buffers, developers can avoid file corruption and successfully download files from AJAX responses in JavaScript. This method is applicable to various file types, with the Blob's type property adjusted as needed. The provided code examples help in understanding core concepts and implementation details.