我为将文件转换为base64进行了很多尝试,但我无能为力吗?
答案 0 :(得分:0)
有一个例子,有人在https://codepen.io/AshV/pen/pjodjV上戴了Codepen
HTML
<input type="file" id="files" name="files" />
<br/>
<textarea id="base64" rows="5"></textarea>
JS
// Check for the File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('files').addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
function handleFileSelect(evt) {
var f = evt.target.files[0]; // FileList object
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var binaryData = e.target.result;
//Converting Binary Data to base 64
var base64String = window.btoa(binaryData);
//showing file converted to base64
document.getElementById('base64').value = base64String;
alert('File converted to base64 successfuly!\nCheck in Textarea');
};
})(f);
// Read in the image file as a data URL.
reader.readAsBinaryString(f);
}
您可以在Codepen上尝试一下,以查看此示例是否有效。
您可能需要以某种方式对其进行调整以适合您的React项目,但基本上这就是您所需要的。