表单提交前预览图像

时间:2011-07-07 08:55:50

标签: jquery django django-templates

我的形式有ImageField。在提交表单之前有没有办法显示所选文件?也许在jQuery中有可能?

我读到我可以用request.FILES以某种方式访问​​这些文件,但我认为在我提交表单之前它将是空的。

1 个答案:

答案 0 :(得分:28)

尝试这个。

<script type="text/javascript">


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

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

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

    </script>

AND HTML在下面。

感谢。

    <form id="form_img">
        <input type='file' onchange="upload_img(this);" />
        <img id="img_id" src="#" alt="your image" />
    </form>

这可能对您有所帮助。

相关问题