js base64转文件流
时间: 2023-10-28 16:01:25 浏览: 42
将Base64字符串转为文件流可以通过以下步骤实现:
1. 将Base64字符串解码为二进制数据,可以使用`atob()`函数。
2. 创建一个Blob对象,将二进制数据传入其中。
3. 创建一个URL对象,使用`URL.createObjectURL()`函数将Blob对象转为URL。
4. 创建一个FileReader对象,使用`readAsArrayBuffer()`函数读取URL对象。
5. 在FileReader对象的`onloadend`事件中获取文件流。
以下是示例代码:
```javascript
function base64ToBlob(base64) {
const binaryStr = atob(base64);
const len = binaryStr.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryStr.charCodeAt(i);
}
return new Blob([bytes]);
}
function base64ToFileStream(base64) {
const blob = base64ToBlob(base64);
const url = URL.createObjectURL(blob);
const reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = function() {
const fileStream = new ReadableStream({
start(controller) {
controller.enqueue(reader.result);
controller.close();
}
});
// do something with fileStream
};
}
```
在上面的示例代码中,`base64ToBlob()`函数将Base64字符串解码为Blob对象,`base64ToFileStream()`函数将Blob对象转为文件流。最终的文件流在`fileStream`变量中,可以根据需求进行后续处理。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)