我试图编写一段代码,允许用户打开文件浏览器并选择要上传到网站的文件。有没有办法确保文件浏览器始终在缩略图视图中打开?在Windows中,视图与上次使用的视图相同。
<form action="demo_form.asp">
Select a file: <input type="file" name="img">
<input type="submit">
</form>
我在Facebook看到它总是以缩略图的形式打开,无论使用的是最后一个视图,它是如何完成的?
答案 0 :(得分:0)
此代码使用HTML5功能,可能无法与旧版浏览器配合使用。
HTML:
<input type="file" style="display:none" id="upload-image" multiple="multiple"></input>
<div id="upload" class="drop-area">
Upload File
</div>
<div id="thumbnail"></div>
CSS:
.drop-area{
width:100px;
height:25px;
border: 1px solid #999;
text-align: center;
padding:10px;
cursor:pointer;
}
#thumbnail img{
width:100px;
height:100px;
margin:5px;
}
canvas{
border:1px solid red;
}
jQuery的:
jQuery(function($){
var fileDiv = document.getElementById("upload");
var fileInput = document.getElementById("upload-image");
console.log(fileInput);
fileInput.addEventListener("change",function(e){
var files = this.files
showThumbnail(files)
},false)
fileDiv.addEventListener("click",function(e){
$(fileInput).show().focus().click().hide();
e.preventDefault();
},false)
fileDiv.addEventListener("dragenter",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("dragover",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("drop",function(e){
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
showThumbnail(files)
},false);
function showThumbnail(files){
for(var i=0;i<files.length;i++){
var file = files[i]
var imageType = /image.*/
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
// image.classList.add("")
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function(aImg){
return function(e){
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload= function(){
ctx.drawImage(image,100,100)
}}}});