javascript 如何从本地机器加载图像到JS对象避免加载到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11603644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load images from the local machine to JS object avoiding loading to the server
提问by hexonxons
I want to load an image file from the computer directly to any js object without using any server-side component. For example, I want to select a picture from the local machine and display it on a webpage. Is there a way to avoid file upload to the server?
我想从计算机直接加载图像文件到任何 js 对象,而不使用任何服务器端组件。例如,我想从本地机器中选择一张图片并将其显示在网页上。有没有办法避免文件上传到服务器?
In fact I want to write a kind of multiple image loader, but before loading to the server I want to rotate some images, create an xml-file with some data like user id, image file names list and to zip all images and this xml and then send it to the server. How can I do that on the client side?
事实上,我想编写一种多图像加载器,但在加载到服务器之前我想旋转一些图像,创建一个包含用户 ID、图像文件名列表等数据的 xml 文件,并压缩所有图像和这个 xml然后将其发送到服务器。我怎样才能在客户端做到这一点?
回答by Alnitak
There is a way with HTML5, but it requires the user to have dropped the file into a drop target or used a <input type="file"/>
box, since otherwise it would be a security issue.
HTML5 有一种方法,但它要求用户将文件拖放到拖放目标中或使用一个<input type="file"/>
盒子,否则这将是一个安全问题。
Using the File
API you can read files, and specifically you can use the FileReader.readAsDataURL
method to set the content as a data:
URL for the image tag.
使用File
API 可以读取文件,特别是可以使用该FileReader.readAsDataURL
方法将内容设置data:
为图像标签的URL。
Here's an example:
下面是一个例子:
$('#f').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
console.dir(ev2);
$('#i').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});?
回答by josh3736
Using the new File APIs, it is possible to access content from the local disk.
使用新的文件 API,可以从本地磁盘访问内容。
You put a traditional <input type="file">
upload field on your page, and handle the onchange
event.
您<input type="file">
在页面上放置了一个传统的上传字段,并处理该onchange
事件。
MDN has a good writeup with all of the details.
Your event handler gets a FileList
containing Files
. From there, you can call FileReader.readAsDataURL(File)
to fetch the content of the image and then pass that data URL to an <img>
or a <canvas>
to do rotation.
您的事件处理程序获得一个FileList
包含Files
. 从那里,您可以调用FileReader.readAsDataURL(File)
以获取图像的内容,然后将该数据 URL 传递给 an<img>
或 a<canvas>
以进行旋转。
回答by Musa
You can use createObjectURLmethod of the window.URL object, this doesn't have much browser support though
您可以使用window.URL 对象的createObjectURL方法,虽然这没有太多浏览器支持
http://jsfiddle.net/LvAqp/only works in chrome and firefox
http://jsfiddle.net/LvAqp/仅适用于 chrome 和 firefox