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

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

這個(gè)是圖片時(shí)的預(yù)覽圖

$('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]);
 }
});

這是添加影片預(yù)覽圖

$(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();
});

只是當(dāng)初我寫(xiě)的時(shí)候影片上傳和照片上傳是分開(kāi)的:

<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>

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

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

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

回答
編輯回答
青檸

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

$('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
編輯回答
舊酒館

通過(guò) event.files[0].type 判斷,應(yīng)該是 image/*video/*

2017年8月8日 09:03