2012-07-17 101 views
0

我已經實現了將圖片上傳到瀏覽器並顯示爲縮略圖的代碼。然後它也可以拖入畫布區域。但是當我用chrome運行它時,它並沒有打開窗口來上傳文件。首先上傳圖片,然後創建縮略圖。但它不適用於Chrome。上傳圖片並在瀏覽器窗口中顯示

這裏是我的代碼,

<!DOCTYPE HTML> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Drag Demo</title> 
<link href="copy.css" rel="stylesheet" type="text/css" /> 
</head> 
<body> 
<div class="container"> 
<div style = "border:2px solid black;"> 
<canvas id = "canvas" style = "position:relative;width:300px;height:300px;top:0px;left:500px; border:2px solid black;" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </canvas>  
</div> 
<div> 
    <input type="file" id="fileElem" accept="image/*" style="display:none" > 
    <div id="fileSelect" class="drop-area">Select some files</div> 
</div> 
    <div id="thumbnail"></div> 
</div> 


<script type="text/javascript"> 
function dragIt(event) { 
event.dataTransfer.setData("Text", event.target.id) 
}; 


function dropIt(event) { 
    var theData = event.dataTransfer.getData("Text"); 
    dt = document.getElementById(theData); 
    event.preventDefault(); 
    var c = document.getElementById("canvas"); 
    var ctx = c.getContext('2d'); 
    ctx.drawImage(dt, 100, 0,dt.width,dt.height);  
}; 


var count = 0; 
var fileSelect = document.getElementById("fileSelect"), 
fileElem = document.getElementById("fileElem"); 


fileElem.addEventListener("click",function(e){ 
    var files = this.files 
    handleFiles(files) 
},false) 


fileSelect.addEventListener("click", function (e) { 
    fileElem.click(); 
    e.preventDefault(); 
}, false); 


function handleFiles(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"); 
    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)) 
    image.id = count; 
    count++; 
    image.draggable = true; 
    image.ondragstart = dragIt; 
    var ret = reader.readAsDataURL(file); 
    } 
} 

</script> 

</body> 
</html> 
+0

上面的代碼在Firefox中工作!] – MJQ 2012-07-17 15:59:02

+0

我幫不了你,因爲我在我的手機上,但嘗試調試代碼。在每行之後使用alert()或console.log(),看看哪個部分沒有執行。 – 2012-07-17 16:06:03

+0

我已經試過了!當fileElem.click()執行時,它會進入事件,並在Firefox中打開一個窗口來選擇文件。但在鉻,它遵循相同,但窗口不打開文件選擇! – MJQ 2012-07-17 16:08:50

回答

-1

的服務器上只需運行的代碼,它會工作!

相關問題