2014-12-05 90 views
1

我們如何可以強制返回圖像類型(如果萬一它不返回),同時使用readAsDataURL讀取圖像,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

如果可能的話,可以張貼'js'?謝謝 – guest271314 2014-12-05 06:24:07

回答

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對象返回其具有mime類型以及一個base64字符串,則可以使用此功能提取:

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

+0

在sony xperia L版本4.1上測試過,靜止圖像類型在報警時爲空:( – user1850796 2014-12-05 08:11:32

+0

@ user1850796當你做'alert(JSON.stringify(file))'時,你會得到什麼? – 2014-12-05 08:28:25

+0

它返回文件數組,大小,LastModifiedDate和類型 但類型爲空(type =「」)。 on Android(4.2)native瀏覽器 – 2014-12-05 08:49:22