UPD TypeScript版本也可在答案
现在我通过这一行获取File object:
file = document.querySelector('#files > input[type="file"]').files[0]
我需要通过json在基数64发送这个文件。我应该怎么做才能将其转换为base64字符串?
UPD TypeScript版本也可在答案
现在我通过这一行获取File object:
file = document.querySelector('#files > input[type="file"]').files[0]
我需要通过json在基数64发送这个文件。我应该怎么做才能将其转换为base64字符串?
当前回答
const fileInput = document.querySelector('input');
fileInput.addEventListener('change', (e) => {
// get a reference to the file
const file = e.target.files[0];
// encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
// use a regex to remove data url part
const base64String = reader.result
.replace('data:', '')
.replace(/^.+,/, '');
// log to console
// logs wL2dvYWwgbW9yZ...
console.log(base64String);
};
reader.readAsDataURL(file);});
其他回答
const fileInput = document.querySelector('input');
fileInput.addEventListener('change', (e) => {
// get a reference to the file
const file = e.target.files[0];
// encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
// use a regex to remove data url part
const base64String = reader.result
.replace('data:', '')
.replace(/^.+,/, '');
// log to console
// logs wL2dvYWwgbW9yZ...
console.log(base64String);
};
reader.readAsDataURL(file);});
使用这种方法将任何文件转换为base64
_fileToBase64(file: File) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.toString().substr(reader.result.toString().indexOf(',') + 1));
reader.onerror = error => reject(error);
});
}
打印稿版本
const file2Base64 = (file:File):Promise<string> => {
return new Promise<string> ((resolve,reject)=> {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result?.toString() || '');
reader.onerror = error => reject(error);
})
}
这是
// fileObj: File
const base64 = window.URL.createObjectURL(fileObj);
// You can use it with <img src={base64} />
下面是我写的几个函数,用于获得json格式的文件,可以轻松传递:
//takes an array of JavaScript File objects
function getFiles(files) {
return Promise.all(files.map(getFile));
}
//take a single JavaScript File object
function getFile(file) {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
reader.onload = function () {
//This will result in an array that will be recognized by C#.NET WebApi as a byte[]
let bytes = Array.from(new Uint8Array(this.result));
//if you want the base64encoded file you would use the below line:
let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));
//Resolve the promise with your custom file structure
resolve({
bytes,
base64StringFile,
fileName: file.name,
fileType: file.type
});
}
reader.readAsArrayBuffer(file);
});
}
//using the functions with your file:
file = document.querySelector('#files > input[type="file"]').files[0]
getFile(file).then((customJsonFile) => {
//customJsonFile is your newly constructed file.
console.log(customJsonFile);
});
//if you are in an environment where async/await is supported
files = document.querySelector('#files > input[type="file"]').files
let customJsonFiles = await getFiles(files);
//customJsonFiles is an array of your custom files
console.log(customJsonFiles);