[英]Is it possible to load an image into a web page locally?
The idea is to take an image from a user's machine and allow them to display the image in a webpage. 这个想法是从用户的机器上获取图像,并允许他们在网页中显示图像。 I do not want to send the image back to the server.
我不想将图像发送回服务器。
An upload button will exist. 将存在一个上传按钮。 It should just update the page content dynamically.
它应该只是动态地更新页面内容。
Can this be done with HTML5 localstorage or anything? 可以使用HTML5 localstorage或其他方式完成此操作吗?
FileReader is capable of doing this. FileReader能够做到这一点。 Here's sample code:
这是示例代码:
<input type="file" id="files" name="files[]" multiple />
<img id="image" />
<script>
function onLoad(evt) {
/* do sth with evt.target.result - it image in base64 format ("data:image/jpeg;base64,....") */
localStorage.setItem('image', evt.target.result);
document.getElementById('image').src = evt.target.result;
};
function handleFileUpload(evt) {
var files = evt.target.files; // FileList object
for (var i = 0; i < files.length; i++) {
var f = files[i];
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = onLoad;
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileUpload, false);
var image = localStorage.getItem('image');
if (image !== null) {
document.getElementById('image').src = image;
}
</script>
Yeah absolutely, providing you have a cutting edge browser (Chrome or Firefox). 是的,绝对可以,只要您拥有最先进的浏览器(Chrome或Firefox)。
You want to use FileReader
and readAsDataURL()
. 您要使用
FileReader
和readAsDataURL()
。 Take a look at the third example in this tutorial: 看一下本教程中的第三个示例:
http://www.html5rocks.com/en/tutorials/file/dndfiles/ http://www.html5rocks.com/en/tutorials/file/dndfiles/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.