有没有办法让用户在上传到服务器之前查看他们即将上传客户端的图像? [英] Is there a way to let a user view an image they are about to upload client side before uploading to the server?

查看:164
本文介绍了有没有办法让用户在上传到服务器之前查看他们即将上传客户端的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户上传图片时,有没有办法可以加载图片客户端并先将其显示给他们,然后再将其上传到服务器?最好只使用javascript / jquery,但使用flash也是可以接受的。

When a user is uploading an image, is there a way I can load the image client side and show it to them first, before uploading it to the server? Preferably using javascript/jquery only, but using flash would be acceptable too.

推荐答案

有可能使用新的 FileReader 界面,目前适用于Firefox 。

It is possible with the new FileReader interface defined in HTML5 and works on Firefox currently.

文件输入具有关联的文件属性,该属性跟踪当前为该输入选择的文件列表。要显示此列表中的文件,请创建一个新的 FileReader 对象,初始化其 onload 事件处理程序,然后读取该文件作为数据URL。

A file input has an associated files property which tracks the list of files currently selected for that input. To display a file from this list, create a new FileReader object, initialize its onload event handler, and read the file as a data URL.

// get the first file, foo is a file input field
var file = document.getElementById('foo').files[0];

// setup the reader and the load complete callback
var reader = new FileReader();
reader.onload = function(e) {
    var image = new Image();
    // string representing the image
    image.src = e.target.result;
    document.body.appendChild(image);
};

// read the file as a data url
reader.readAsDataURL(file);

加载文件后,您将可以访问数据网址方案中的内容,例如:

Once the file is loaded, you will have access to its contents in a data url scheme, for instance:

data:image/jpeg;base64,...aqHI7sNyPGFjdtQvFr/2Q==

创建一个新图像并将其 src 属性设置为此数据字符串。

Create a new Image and set its src attribute to this data string.

查看此处的工作示例仅限Firefox

这篇关于有没有办法让用户在上传到服务器之前查看他们即将上传客户端的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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