Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - is it possible to preview local images before uploading them via a form?

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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!
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...