你火的功能,我用下面的代碼這裏面工作。我喜歡將函數放在body上,這樣即使通過AJAX添加了類,「change」命令仍然會觸發事件。
我的方法確實使用jQuery。
HTML:
<input class="text-input" class="classhere" type="text" name="logo" id="logo" />
<div class="imagearea"></div>
JS:
$("body").on("change",".classhere",function(){
//Equivalent of getElementById
var fileInput = $(this)[0];//returns a HTML DOM object by putting the [0] since it's really an associative array.
var file = fileInput.files[0]; //there is only '1' file since they are not multiple type.
var reader = new FileReader();
reader.onload = function(e) {
// Create a new image.
var img = new Image();
img.src = reader.result;
$(".imagearea").html(img);
}
reader.readAsDataURL(file);//attempts to read the file in question.
});
此方法使用HTML5文件系統API的讀取圖像,並把它變成一個新的JavaScript的img對象。這裏的關鍵是readAsDataURL。如果您使用鉻檢查器,您會注意到圖像以base64編碼存儲。
讀者是異步,這就是爲什麼它使用onload回調函數。因此,請確保任何需要圖像的重要代碼位於onLoad內,否則您可能會收到意想不到的結果。
你目前的JavaScript代碼在哪裏? –
添加代碼。到目前爲止你做了什麼?什麼沒有用?這聽起來像是應該在服務器端完成的事情,因爲簡單地將文件名插入到「字段中不會」上傳「它。 – Sumurai8
您無法直接訪問用戶文件系統中的文件。閱讀關於FileReader API。看看這個例子:http://jsfiddle.net/VM7sy/。閱讀[更多](https://developer.mozilla.org/en-US/docs/Web/API/FileReader)。 – dfsq