2012-01-04 74 views
3

我正在使用HTML表單上傳圖像文件。現在我正在使用服務器端驗證來允許文件類型。但我想在客戶端驗證它。我在某些網站上看到,當我們選擇文件時,其他文件類型會灰顯。我認爲這是一個很酷的選擇。當我通過谷歌走,我發現這個將文件上傳類型限制爲僅限圖像

<input id="my_file_element" type="file" name="file_0" accept="image/*"> 

但是這個我得到「所有文件」選項,以便達我就可以使其他的文件。我不需要那個。無論發生什麼事,用戶都應該被允許從他們的計算機中僅選擇圖像文件。你們有沒有辦法做到這一點?

這就是我的意思是灰色的。 enter image description here

+0

我在Firefox試過了,它在那裏工作正常。你使用的是什麼瀏覽器? – 2012-01-04 20:52:31

+0

您可以使用javascript來檢查文件格式的擴展名。我會給你一些代碼,但我吮吸在JavaScript。如果你喜歡,也許jQuery可以工作。 – Different55 2012-01-04 20:56:40

+0

@dotweb:我使用谷歌瀏覽器..在Firefox中可以使用「所有文件」選項並選擇其他文件? – Deepak 2012-01-04 20:56:50

回答

3

accept屬性是HTML5功能,因此很多瀏覽器都不支持此屬性。

恐怕,只要我記得,獲得更好的文件上傳對話框(文件類型過濾器,多個文件...)的唯一方法就是使用Flash對象。

+0

你可以檢查我的編輯?我已經上傳了一張應該看起來如何的圖片。我認爲他們在這裏沒有使用閃存,因爲接口來自MAC而不是閃存。我是誰? – Deepak 2012-01-04 21:13:48

0
Here is the HTML for image upload, By default it will show image files only in browsing window becauase we have put accept="image/*" . But still we can change it from the dropdown and it will show all files. So the Javascript part validates whether the selected file is an actual image or not. 

<div class="col-sm-8 img-upload-section"> 
    <input name="image3" type="file" accept="image/*" id="menu_images"/> 
    <img id="menu_image" class="preview_img" /> 
    <input type="submit" value="Submit" /> 
</div> 

Here on the change event first we are checking the size of the image. And in the second if condition we are checking whether it is an image file or not. 
this.files[0].type.indexOf("image") will be "-1" if it is not an image file. 

    document.getElementById("menu_images").onchange = function() { 
     var reader = new FileReader(); 
     if(this.files[0].size>528385){ 
      alert("Image Size should not be greater than 500Kb"); 
      $("#menu_image").attr("src","blank"); 
      $("#menu_image").hide(); 
      $('#menu_images').wrap('<form>').closest('form').get(0).reset(); 
      $('#menu_images').unwrap();  
      return false; 
     } 
     if(this.files[0].type.indexOf("image")==-1){ 
      alert("Invalid Type"); 
      $("#menu_image").attr("src","blank"); 
      $("#menu_image").hide(); 
      $('#menu_images').wrap('<form>').closest('form').get(0).reset(); 
      $('#menu_images').unwrap();   
      return false; 
     } 
     reader.onload = function (e) { 
      // get loaded data and render thumbnail. 
      document.getElementById("menu_image").src = e.target.result; 
      $("#menu_image").show(); 
     }; 

     // read the image file as a data URL. 
     reader.readAsDataURL(this.files[0]); 
    }; 
+0

雖然此代碼可能有助於解決問題,但 提供了關於_why_和/或_how_的其他上下文,回答該問題將顯着提高其長期價值。請[編輯]你的答案,添加一些 的解釋。 – 2016-07-04 16:45:20