在使用readAsDataURL读取图像时,我们如何强制返回图像类型(如果它没有返回),
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
$("#file").on("change", function(event) {
event.preventDefault();
var output = document.getElementById("result");
existingNode = document.getElementById("addMore");
var files = event.target.files;
for (var i = 0; i < files.length; i++)
{
var file = files[i];
var picReader = new FileReader();
picReader.onload = function(event) {
var picFile = event.target;
var formElement = document.getElementById("submitForm");
var dataToBeSent = new FormData(formElement);
count++;
var div = document.createElement("div");
div.innerHTML = '<div class="fl pu_mr1 pu_mr2 wrap' + count + '">' + '<div class="photobox posrel">' + '<div class="posabs txtc fontlig color2 f14 lh30 pum35 dispnone retryMessage"><i class="up_sprite pu_retry pu_mt2"></i>Retry</div>' + "<img class='classimg1 opa50 uploading" + count + "' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>" + '<div class="posabs pu_pos1" onclick="deleteThisPhoto(' + count + ')"><a href="#" class="up_sprite pu_cross"></a></div>' + '<div class="posabs fullwid pu_pos2 uploadingBar' + count + '">' + '<div class="wid80p brdr12">' + '<div class="bg7 hgt10 mrl0 uploadingPercent' + count + '" style="width:0px;"></div>' + '</div></div></div></div>';
output.insertBefore(div, existingNode);
generatingDiv.innerHTML = "";
formDataArray[count] = dataToBeSent;
};
picReader.readAsDataURL(file); //Read the image
}
答案 0 :(得分:1)
File
对象具有type
属性,其中包含mime类型:
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileType = file.type;
console.log(fileType); // image/png
}
FileReader
对象返回一个base64字符串,该字符串也具有mime类型,您可以使用此函数提取该字符串:
function base64MimeType(encoded) {
if (!encoded) return;
var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);
if (mime && mime.length) return mime[1];
}
var picReader = new FileReader();
picReader.readAsDataURL(file);
var base64 = picReader.result;
console.log(base64MimeType(base54)); // image/png
JSFiddle演示:http://jsfiddle.net/mr2g5dx1/2/
这是我创建的一个小模块:https://github.com/miguelmota/base64mime