有没有办法让用户在上传到服务器之前查看他们即将上传客户端的图像?

问题描述:

当用户上传图片时,有没有办法可以加载图片客户端并先将其显示给他们,然后再将其上传到服务器?最好只使用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