上传前预览图像 [英] Preview images before upload

查看:84
本文介绍了上传前预览图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含四个图像的页面供用户选择.我希望用户能够在上传之前预览网站上的每张图片.

I have a page with four images for the user to select. I want the user to be able to preview each image on the site before upload.

下面的JavaScript代码仅适用于一张图片,但我希望它适用于通过<input type="file">上传的多张图片.

The JavaScript code below works for only one image but I would like it to work for multiple images uploaded via <input type="file">.

什么是最好的方法?

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#output').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#file-input").change(function () {
    readURL(this);
});

推荐答案

这是您的 jQuery 版本.我认为这是最简单的事情.

Here is jQuery version for you. I think it more simplest thing.

$(function() {
    // Multiple images preview in browser
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#gallery-photo-add').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>

这篇关于上传前预览图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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