<input type="file" id="asd"/>
一旦用户选择(在提交表单之前),我想在 base64 中获取图片
类似的东西:
$(input).on('change',function(){
var data = $(this).val().base64file(); // it is not a plugin is just an example
alert(data);
});
我读过有关File API和其他内容的文章,我想要一个简单的跨浏览器解决方案(明显排除IE6 / IE7)
任何帮助表示感谢。
答案 0 :(得分:176)
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:一个base64编码的图像(String)4/3原始图像数据的大小)
Check this answer for multiple images upload
浏览器支持:http://caniuse.com/#search=file%20api
更多信息:https://developer.mozilla.org/en-US/docs/Web/API/FileReader
答案 1 :(得分:33)
你需要什么:)你可以选择回调版或Promise版。请注意,promises只能在IE中使用Promise polyfill lib。您可以在页面上放置一次此代码,此函数将出现在您的所有文件中。
当加载进度停止时会触发loadend事件 资源(例如在“错误”,“中止”或“加载”之后) 调度)
回调版
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);
})
});
承诺版
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
<input type="file" id="asd" multiple/>
答案 2 :(得分:5)
在这种情况下使用Deferred Object并返回承诺是有用的:
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();
}
以上功能可以这样使用:
var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
alert(base64Data);
});
或者在你的情况下:
$(input).on('change',function(){
readImage($(this)).done(function(base64Data){ alert(base64Data); });
});
答案 3 :(得分:1)
CLIPS> (defglobal ?*id* = 0)
CLIPS>
(deffunction next-id ()
(bind ?*id* (+ ?*id* 1)))
CLIPS>
(deftemplate employee
(slot employee-id (default-dynamic (next-id)))
(slot employee-name)
(slot Role)
(slot Designation))
CLIPS>
(deffacts Employees
(employee (employee-name X) (Role CS) (Designation TA))
(employee (employee-name Y) (Role CS) (Designation SA))
(employee (employee-name Z) (Role CIS) (Designation TA))
(employee (employee-name W) (Role SE) (Designation SA))
(employee (employee-name Q) (Role CIS) (Designation TA))
(employee (employee-name U) (Role CS) (Designation TA)))
CLIPS> (reset)
CLIPS> (facts)
f-0 (initial-fact)
f-1 (employee (employee-id 1) (employee-name X) (Role CS) (Designation TA))
f-2 (employee (employee-id 2) (employee-name Y) (Role CS) (Designation SA))
f-3 (employee (employee-id 3) (employee-name Z) (Role CIS) (Designation TA))
f-4 (employee (employee-id 4) (employee-name W) (Role SE) (Designation SA))
f-5 (employee (employee-id 5) (employee-name Q) (Role CIS) (Designation TA))
f-6 (employee (employee-id 6) (employee-name U) (Role CS) (Designation TA))
For a total of 7 facts.
CLIPS>
答案 4 :(得分:0)
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
/* Simple */
function previewImage( image, preview, string )
{
var preview = document.querySelector( preview );
var fileImage = image.files[0];
var reader = new FileReader();
reader.addEventListener( "load", function() {
preview.style.height = "100";
preview.title = fileImage.name;
// convert image file to base64 string
preview.src = reader.result;
/* --- */
document.querySelector( string ).value = reader.result;
}, false );
if ( fileImage )
{
reader.readAsDataURL( fileImage );
}
}
document.querySelector( "#imageID" ).addEventListener( "change", function() {
previewImage( this, "#imagePreviewID", "#imageStringID" );
} )
/* Simple || */
<form>
File Upload: <input type="file" id="imageID" /><br />
Preview: <img src="#" id="imagePreviewID" /><br />
String base64: <textarea id="imageStringID" rows="10" cols="50"></textarea>
</form>
答案 5 :(得分:0)
功能使用jquery将图像转换为base64(您可以转换为vanila js)。希望对你有帮助!
用法:input is your nameId input has file image
<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
async function converImageToBase64(inputId) {
let image = $('#'+inputId)[0]['files']
if (image && image[0]) {
const reader = new FileReader();
return new Promise(resolve => {
reader.onload = ev => {
resolve(ev.target.result)
}
reader.readAsDataURL(image[0])
})
}
}
async function proccessData() {
const image = await converImageToBase64('asd')
console.log(image)
}
</script>
示例:converImageToBase64('yourFileInputId')
答案 6 :(得分:0)
HTML 文件输入
<style>
.upload-button {
background-color: grey;
}
.upload-button input{
display:none;
}
</style>
<label for="upload-photo" class="upload-button">
Upload file
<input
type="file"
id="upload-photo"
</input>
</label>
JS
document.getElementById("upload-photo").addEventListener("change", function({target}){
if (target.files && target.files.length) {
try {
const uploadedImageBase64 = await convertFileToBase64(target.files[0]);
//do something with above data string
} catch() {
//handle error
}
}
})
function convertFileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
});
}