Js通过预览拖放图像/视频上传

时间:2017-07-27 22:01:29

标签: javascript image video drag-and-drop

我的目标是为视频和图片添加一个拖放上传框,以便按照框的确切形状和大小填充文件。

您可以在此处看到该代码段:http://jsfiddle.net/ELcf6/4/

无法弄清楚,如何将相同的视频上传功能添加到同一个框中。非常感谢任何帮助。

以下是片段:



var imageLoader = document.getElementById('filePhoto');
    imageLoader.addEventListener('change', handleImage, false);

function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
        
        $('.uploader img').attr('src',event.target.result);
    }
    reader.readAsDataURL(e.target.files[0]);
}

.uploader {position:relative; overflow:hidden; width:300px; height:350px; background:#f3f3f3; border:2px dashed #e8e8e8;}

#filePhoto{
    position:absolute;
    width:300px;
    height:400px;
    top:-50px;
    left:0;
    z-index:2;
    opacity:0;
    cursor:pointer;
}

.uploader img{
    position:absolute;
    width:302px;
    height:352px;
    top:-1px;
    left:-1px;
    z-index:1;
    border:none;
}

<div class="uploader" onclick="$('#filePhoto').click()">
    click here or drag here your images for preview and set userprofile_picture data
    <img src=""/>
    <input type="file" name="userprofile_picture"  id="filePhoto" />
</div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

作为一项建议,并非如此,但是作为必须先进行客户端上传的人,我发现使用http://www.dropzonejs.com/非常容易。

答案 1 :(得分:0)

您要搜索的关键字是: createObjectURL

https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

但是,浏览器必须支持它。

答案 2 :(得分:0)

好的,所以你试图从视频文件中提取图像数据,这不一定有效。您实际需要的是一个隐藏的视频字段和html5画布。当您放下视频文件时,您填充视频源,然后一旦检测到任何图像数据,您就可以通过画布播放它,就像您将能够以相同的方式显示它图片。关于如何在StackOverflow上通过画布播放视频有很多答案,而且实际上并没有那么困难。

答案 3 :(得分:0)

我已经更新了你的JSFiddle,有点做你想做的事Jsfiddle 我只测试了它的工作原理。根据您的需要更新它。

function handleImage(e) {
    var filetype = imageLoader.files[0].type;
var reader = new FileReader();
reader.onload = function (event) {
    if(filetype.indexOf("image") > -1){
    $('.uploader img').attr('src',event.target.result);
    }else if(filetype.indexOf("video") > -1){

    $('.uploader video')[0].src =reader.result; 
    }

}
reader.readAsDataURL(e.target.files[0]);

}

在脚注上确保删除兼容的视频。并非所有视频文件都会显示。

相关问题