如何将 Base64 字符串转换为 javascript 文件对象,就像从文件输入表单一样?
How to convert Base64 String to javascript file object like as from file input form?
我想将从文件(例如:"AAAAA....~")中提取的 Base64String 转换为 javascript 文件对象。
javascript文件对象我的意思是像这样的代码:
HTML:
<input type="file" id="selectFile" >
JS:
$('#selectFile').on('change', function(e) {
var file = e.target.files[0];
console.log(file)
}
'file' 变量是一个 javascript 文件对象。所以我想像那样将 base64 字符串转换为 javascript 文件对象。
我只想通过解码 base64 字符串(由文件中的其他应用程序编码)来获取文件对象,而无需 html 文件输入形式。
谢谢。
方式一:只对dataURL有效,其他类型url无效。
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//Usage example:
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');
console.log(file);
方式 2: 适用于任何类型的 url,(http url、dataURL、blobURL 等...)
//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename,{type:mimeType});})
);
}
//Usage example:
urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')
.then(function(file){ console.log(file);});
注意,
JAVASCRIPT
<script>
function readMtlAtClient(){
mtlFileContent = '';
var mtlFile = document.getElementById('mtlFileInput').files[0];
var readerMTL = new FileReader();
// Closure to capture the file information.
readerMTL.onload = (function(reader) {
return function() {
mtlFileContent = reader.result;
mtlFileContent = mtlFileContent.replace('data:;base64,', '');
mtlFileContent = window.atob(mtlFileContent);
};
})(readerMTL);
readerMTL.readAsDataURL(mtlFile);
}
</script>
HTML
<input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput"
onchange="readMtlAtClient()" accept=".mtl"/>
然后 mtlFileContent 将您的文本作为解码字符串!
const url = 'data:image/png;base6....';
fetch(url)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], "File name",{ type: "image/png" })
})
Base64 字符串 -> Blob -> 文件。
我有一个非常相似的要求(从外部 xml 导入文件导入 base64 编码图像。在使用 xml2json-light library 转换为 json 对象后,我能够利用上面 cuixiping 的回答中的见解将传入的 b64 编码图像转换为文件对象。
const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
mimeType = 'image/jpeg';
}
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], imgName, {type: mimeType});
我传入的 json 对象在被 xml2json-light 转换后有两个属性:FileName 和 _@ttribute(它是包含在正文中的 b64 图像数据传入元素。)我需要根据传入的 FileName 扩展名生成 mime 类型。一旦我从 json 对象中获得所有片段 extracted/referenced ,生成与我现有的 类 完全兼容的新文件对象是一个简单的任务(使用 cuixiping 提供的代码参考)期望从浏览器元素生成文件对象。
希望这对其他人有所帮助。
这是最新的 async/await
模式解决方案。
export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {
const res: Response = await fetch(dataUrl);
const blob: Blob = await res.blob();
return new File([blob], fileName, { type: 'image/png' });
}
这是上面@cuixiping 接受的答案的 Typescript 版本,现在使用 Buffer 而不是 atob()
我看到了使用 TypeScript 中的 atob() 的弃用警告,尽管它并未完全弃用。只有一个过载是。但是,我将我的转换为使用 Buffer 的弃用警告建议。它看起来更干净,因为它不需要额外的循环来转换每个字符。
/***
* Converts a dataUrl base64 image string into a File byte array
* dataUrl example:
* data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIsAAACLCAYAAABRGWr/AAAAAXNSR0IA...etc
*/
dataUrlToFile(dataUrl: string, filename: string): File | undefined {
const arr = dataUrl.split(',');
if (arr.length < 2) { return undefined; }
const mimeArr = arr[0].match(/:(.*?);/);
if (!mimeArr || mimeArr.length < 2) { return undefined; }
const mime = mimeArr[1];
const buff = Buffer.from(arr[1], 'base64');
return new File([buff], filename, {type:mime});
}
在文件的顶部,您需要进行导入以使输入愉快。
import { Buffer } from 'buffer';
不需要特殊的 npm 包。
const file = new File([
new Blob(["decoded_base64_String"])
], "output_file_name");
您可以使用像 this 这样的库来解码和编码 base64 到 arrayBuffer。
我想将从文件(例如:"AAAAA....~")中提取的 Base64String 转换为 javascript 文件对象。
javascript文件对象我的意思是像这样的代码:
HTML:
<input type="file" id="selectFile" >
JS:
$('#selectFile').on('change', function(e) {
var file = e.target.files[0];
console.log(file)
}
'file' 变量是一个 javascript 文件对象。所以我想像那样将 base64 字符串转换为 javascript 文件对象。
我只想通过解码 base64 字符串(由文件中的其他应用程序编码)来获取文件对象,而无需 html 文件输入形式。
谢谢。
方式一:只对dataURL有效,其他类型url无效。
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//Usage example:
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');
console.log(file);
方式 2: 适用于任何类型的 url,(http url、dataURL、blobURL 等...)
//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename,{type:mimeType});})
);
}
//Usage example:
urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')
.then(function(file){ console.log(file);});
注意,
JAVASCRIPT
<script>
function readMtlAtClient(){
mtlFileContent = '';
var mtlFile = document.getElementById('mtlFileInput').files[0];
var readerMTL = new FileReader();
// Closure to capture the file information.
readerMTL.onload = (function(reader) {
return function() {
mtlFileContent = reader.result;
mtlFileContent = mtlFileContent.replace('data:;base64,', '');
mtlFileContent = window.atob(mtlFileContent);
};
})(readerMTL);
readerMTL.readAsDataURL(mtlFile);
}
</script>
HTML
<input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput"
onchange="readMtlAtClient()" accept=".mtl"/>
然后 mtlFileContent 将您的文本作为解码字符串!
const url = 'data:image/png;base6....';
fetch(url)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], "File name",{ type: "image/png" })
})
Base64 字符串 -> Blob -> 文件。
我有一个非常相似的要求(从外部 xml 导入文件导入 base64 编码图像。在使用 xml2json-light library 转换为 json 对象后,我能够利用上面 cuixiping 的回答中的见解将传入的 b64 编码图像转换为文件对象。
const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
mimeType = 'image/jpeg';
}
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], imgName, {type: mimeType});
我传入的 json 对象在被 xml2json-light 转换后有两个属性:FileName 和 _@ttribute(它是包含在正文中的 b64 图像数据传入元素。)我需要根据传入的 FileName 扩展名生成 mime 类型。一旦我从 json 对象中获得所有片段 extracted/referenced ,生成与我现有的 类 完全兼容的新文件对象是一个简单的任务(使用 cuixiping 提供的代码参考)期望从浏览器元素生成文件对象。
希望这对其他人有所帮助。
这是最新的 async/await
模式解决方案。
export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {
const res: Response = await fetch(dataUrl);
const blob: Blob = await res.blob();
return new File([blob], fileName, { type: 'image/png' });
}
这是上面@cuixiping 接受的答案的 Typescript 版本,现在使用 Buffer 而不是 atob()
我看到了使用 TypeScript 中的 atob() 的弃用警告,尽管它并未完全弃用。只有一个过载是。但是,我将我的转换为使用 Buffer 的弃用警告建议。它看起来更干净,因为它不需要额外的循环来转换每个字符。
/***
* Converts a dataUrl base64 image string into a File byte array
* dataUrl example:
* data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIsAAACLCAYAAABRGWr/AAAAAXNSR0IA...etc
*/
dataUrlToFile(dataUrl: string, filename: string): File | undefined {
const arr = dataUrl.split(',');
if (arr.length < 2) { return undefined; }
const mimeArr = arr[0].match(/:(.*?);/);
if (!mimeArr || mimeArr.length < 2) { return undefined; }
const mime = mimeArr[1];
const buff = Buffer.from(arr[1], 'base64');
return new File([buff], filename, {type:mime});
}
在文件的顶部,您需要进行导入以使输入愉快。
import { Buffer } from 'buffer';
不需要特殊的 npm 包。
const file = new File([
new Blob(["decoded_base64_String"])
], "output_file_name");
您可以使用像 this 这样的库来解码和编码 base64 到 arrayBuffer。