你火的功能,我用下面的代码这里面工作。我喜欢将函数放在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