上傳照片或影片如果要預覽功能,能怎麼結合?(同一個 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
只是我現在都寫在同一個

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

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

阅读 5.3k
2 个回答

其实就是根据文件类型来判断就可以了。

$('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 处理视频
   }
});

通过 event.files[0].type 判断,应该是 image/*video/*

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题