如何将图像从本地计算机加载到JS对象,避免加载到服务器 [英] How to load images from the local machine to JS object avoiding loading to the server

查看:75
本文介绍了如何将图像从本地计算机加载到JS对象,避免加载到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像文件从计算机直接加载到任何js对象,而不使用任何服务器端组件.例如,我想从本地计算机上选择一张图片并将其显示在网页上.有没有办法避免文件上传到服务器?

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?

事实上,我想编写一种多图像加载器,但是在加载到服务器之前,我想旋转一些图像,创建一个包含一些数据的xml文件,例如用户ID,图像文件名列表并压缩所有图像和这个xml,然后将其发送到服务器.我该如何在客户端上做到这一点?

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?

推荐答案

HTML5有一种方法,但是它要求用户将文件拖放到放置目标中或使用<input type="file"/>框,否则将会是一个安全问题.

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.

使用File API可以读取文件,特别是可以使用FileReader.readAsDataURL方法将内容设置为图像标签的data: URL.

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.

这是一个例子:

$('#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);
});​

http://jsfiddle.net/alnitak/Qszjg/

这篇关于如何将图像从本地计算机加载到JS对象,避免加载到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆