鍍金池/ 問答/PHP  HTML/ 上傳照片或影片如果要預覽功能,能怎麼結合?(同一個 input)

上傳照片或影片如果要預覽功能,能怎麼結合?(同一個 input)

這個是圖片時的預覽圖

$('input[type=file]').change(function() {
   var input = $(this);
   if(!!this.files && !!this.files[0]) {
     var reader = new FileReader();
   reader.onload = function(e) {
       $('#pre' + input.prop('id').substr(4,2)).prop('src', e.target.result);
   }
   reader.readAsDataURL(this.files[0]);
 }
});

這是添加影片預覽圖

$(document).on("change", ".file_multi_video", function(evt) {
  var $source = $('#video_here');
  $('.video_show').show();
  $source[0].src = URL.createObjectURL(this.files[0]);
  $source.parent()[0].load();
});

只是當初我寫的時候影片上傳和照片上傳是分開的:

<input type="file" name="video" class="file_multi_video upload_cover" accept="video/*">
              <video autoplay muted class="video_show displayNone">
                <source src="<?=$editBlog['video'];?>" id="video_here">
              </video>

所以會有兩個上傳 input
只是我現(xiàn)在都寫在同一個

<input type="file" id="file02" name="cover" class="upload_cover" accept="image/jpeg, image/png, image/jpg, video/*">

只是我不知道怎麼整合上傳照片的時候是使用第一個 function
如果是影片上傳則是另一個 function 來預覽?
請問能怎麼實現(xiàn)?
如何在 input change 中判斷?或有其他更好的方法?

回答
編輯回答
青檸

其實就是根據(jù)文件類型來判斷就可以了。

$('input[type=file]').change(function() {
   if(!this.files || !this.files[0]) {
      return;
   }
   var filetype = this.files[0].type;
   if(filetype.indexOf('image') > -1) {
      //todo 處理圖片
   }
   if(filetype.indexOf('video') > -1) {
      //todo 處理視頻
   }
});
2018年4月18日 01:00
編輯回答
舊酒館

通過 event.files[0].type 判斷,應該是 image/*video/*。

2017年8月8日 09:03