jQuery 图像转换为 Base64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17710147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Image convert to Base64
提问by bombastic
<input type="file" id="asd"/>
I would like to get the image in base64once the user chose that (before submitting the form)
一旦用户选择(在提交表单之前),我想在base64 中获取图像
Something like :
就像是 :
$(input).on('change',function(){
var data = $(this).val().base64file(); // it is not a plugin is just an example
alert(data);
});
I read about File API and other stuffs, I would like a simple and cross-browsers solution (IE6/IE7 excluded obviously)
我阅读了文件 API 和其他东西,我想要一个简单的跨浏览器解决方案(显然排除 IE6/IE7)
Any help appreciated thanks.
任何帮助表示感谢。
回答by Roko C. Buljan
function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.addEventListener("load", function(e) {
document.getElementById("img").src = e.target.result;
document.getElementById("b64").innerHTML = e.target.result;
});
FR.readAsDataURL( this.files[0] );
}
}
document.getElementById("inp").addEventListener("change", readFile);
<input id="inp" type='file'>
<p id="b64"></p>
<img id="img" height="150">
(P.S:A base64 encoded image (String) 4/3 the size of the original image data)
(PS:一张base64编码的图片(字符串)原始图片数据大小的4/3)
Check this answer for multiple images upload.
Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
浏览器支持:http: //caniuse.com/#search=file%20api
更多信息在这里:https: //developer.mozilla.org/en-US/docs/Web/API/FileReader
回答by Alex Nikulin
Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.
正是您所需要的:) 您可以选择回调版本或承诺版本。请注意,promise 只能在 IE 中与 Promise polyfill lib 一起使用。您可以将此代码放在页面上一次,此功能将出现在您的所有文件中。
The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)
loadend 事件在资源加载进度停止时触发(例如在“错误”、“中止”或“加载”被分派后)
Callback version
回调版本
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onloadend = function (e) {
callback(e.target.result, e.target.error);
};
reader.readAsDataURL(this);
};
$("#asd").on('change',function(){
var selectedFile = this.files[0];
selectedFile.convertToBase64(function(base64){
alert(base64);
})
});
Promise version
承诺版
File.prototype.convertToBase64 = function(){
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onloadend = function (e) {
resolve({
fileName: this.name,
result: e.target.result,
error: e.target.error
});
};
reader.readAsDataURL(this);
}.bind(this));
};
FileList.prototype.convertAllToBase64 = function(regexp){
// empty regexp if not set
regexp = regexp || /.*/;
//making array from FileList
var filesArray = Array.prototype.slice.call(this);
var base64PromisesArray = filesArray.
filter(function(file){
return (regexp).test(file.name)
}).map(function(file){
return file.convertToBase64();
});
return Promise.all(base64PromisesArray);
};
$("#asd").on('change',function(){
//for one file
var selectedFile = this.files[0];
selectedFile.convertToBase64().
then(function(obj){
alert(obj.result);
});
});
//for all files that have file extention png, jpeg, jpg, gif
this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
objArray.forEach(function(obj, i){
console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
});
});
})
html
html
<input type="file" id="asd" multiple/>
回答by Vasyl Senko
It's useful to work with Deferred Objectin this case, and return promise:
在这种情况下使用延迟对象很有用,并返回承诺:
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr= new FileReader();
fr.onload = function(e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL( files[0] );
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
And above function could be used in this way:
以上函数可以这样使用:
var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
alert(base64Data);
});
Or in your case:
或者在你的情况下:
$(input).on('change',function(){
readImage($(this)).done(function(base64Data){ alert(base64Data); });
});
回答by Vasyl Petrov
<input type="file" onchange="getBaseUrl()">
function getBaseUrl () {
var file = document.querySelector('input[type=file]')['files'][0];
var reader = new FileReader();
var baseString;
reader.onloadend = function () {
baseString = reader.result;
console.log(baseString);
};
reader.readAsDataURL(file);
}