js中将base64图片转成file
时间: 2023-12-30 15:24:10 浏览: 156
在JavaScript中,可以使用以下方法将base64图片转换为file格式:
1. 使用fetch API获取base64图片数据:
```javascript
fetch('data:image/png;base64,iVBORw0KG...') // 替换为你的base64图片数据
.then(response => response.blob())
.then(blob => {
const file = new File([blob], 'image.png', { type: 'image/png' });
console.log(file);
});
```
2. 使用XMLHttpRequest获取base64图片数据:
```javascript
function base64toFile(base64, filename, mimeType) {
const byteCharacters = atob(base64);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: mimeType });
return new File([blob], filename, { type: mimeType });
}
const base64 = 'iVBORw0KG...'; // 替换为你的base64图片数据
const file = base64toFile(base64, 'image.png', 'image/png');
console.log(file);
```
这两种方法都可以将base64图片数据转换为file格式,你可以根据自己的需求选择其中一种方法进行使用。
阅读全文
相关推荐

















