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

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

问题描述

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

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?

附:我知道有一个沙箱,但沙箱必须在一个黑暗、上锁的房间里,所有窗户都涂黑了吗?

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天全站免登陆