通过js将base64转化成文件
时间: 2023-07-28 09:12:05 浏览: 169
可以通过以下步骤将 base64 转换为文件:
1. 将 base64 字符串转换为 ArrayBuffer 对象:
```javascript
function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
```
2. 将 ArrayBuffer 对象转换为 Blob 对象:
```javascript
function arrayBufferToBlob(buffer, type) {
return new Blob([buffer], { type: type });
}
```
3. 将 Blob 对象保存为文件:
```javascript
function saveFile(blob, fileName) {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
```
完整代码如下:
```javascript
function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
function arrayBufferToBlob(buffer, type) {
return new Blob([buffer], { type: type });
}
function saveFile(blob, fileName) {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
// 示例
const base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...';
const arrayBuffer = base64ToArrayBuffer(base64String.split(',')[1]);
const blob = arrayBufferToBlob(arrayBuffer, 'image/png');
saveFile(blob, 'image.png');
```
阅读全文