是否可以在通过表格上传之前预览本地图像? [英] is it possible to preview local images before uploading them via a form?

查看:93
本文介绍了是否可以在通过表格上传之前预览本地图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说,我想使用一个带有一个或多个用于图像的文件输入字段的表单。当这些字段发生变化时,我想在将数据发送到服务器之前显示相关图像的预览。

To be more specific, I want to use a form with one or more file input fields used for images. When those fields are changed, I'd like to show a preview of the associated image, before sending the data to the server.

我尝试过一些javascript方法,但我总是遇到安全错误。
我不介意使用java或flash,只要解决方案适合那些没有它们的用户。 (他们不会得到预览,他们也不会讨厌'安装这个东西'。)

I've tried a number of javascript approaches, but I always run into security errors. I wouldn't mind using java or flash, as long as the solution degraded gracefully for those users who didn't have them. (They wouldn't get previews, and they wouldn't get an annoying 'install this thing' either.)

有没有人以一种简单,可重复使用的方式做到这一点?

Has anyone done this in a simple, reusable way?

PS我知道有一个沙箱,但沙箱是否必须在一个黑暗的,被锁定的房间里,所有的窗户都被涂黑了?

P.S. I know there's a sandbox, but does the sandbox have to be in a dark, locked room with all the windows blacked out?

推荐答案

不需要花哨的东西。你只需要 createObjectURL 函数,它创建一个可以用作图像 src 的URL,并且可以来直接来自本地文件。

No need for fancy stuff. All you need is the createObjectURL function, which creates a URL that can be used as the image src, and can come straight from a local file.

假设您使用文件输入元素从用户的计算机中选择了几张图像(< input type = file/> )。以下是为图像文件创建预览的方法:

Let's say you selected a couple of images from the user's computer using a file input element (<input type="file" />). Here's how you would create previews for image files for it:

function createObjectURL(object) {
    return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}

function revokeObjectURL(url) {
    return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}

function myUploadOnChangeFunction() {
    if(this.files.length) {
        for(var i in this.files) {
            var src = createObjectURL(this.files[i]);
            var image = new Image();
            image.src = src;
            // Do whatever you want with your image, it's just like any other image
            // but it displays directly from the user machine, not the server!
        }
    }
}

这篇关于是否可以在通过表格上传之前预览本地图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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