表单提交前预览图像

问题描述:

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

I have ImageField in my form. Is there any way to show chosen file before submitting a form? Maybe it is possible in jQuery?

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

I read that I can somehow access this files with request.FILES, but I think it will be empty before I will submit form.

试试这个.

function upload_img(input) {
  if (input.files && input.files[0]) {
    var src = URL.createObjectURL(input.files[0])
    $('#img_id').attr('src', src)
  }
}

和 HTML 在下面.

AND HTML is below.

谢谢.

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

这可能对您有所帮助.