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

前端 未结 6 982
不思量自难忘°
不思量自难忘° 2020-12-02 21:07

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 im

6条回答
  •  暖寄归人
    2020-12-02 21:42

    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 (). 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!
            }
        }
    }
    

提交回复
热议问题