HTML input type=file, get the image before submitt

2019-01-07 09:39发布

I'm building a basic social network and in the registration the user uploads a display image. Basically I wanted to display the image, like a preview on the same page as the form, just after they select it and before the form is submitted.

Is this possible?

7条回答
Fickle 薄情
2楼-- · 2019-01-07 10:18

this can be done very easily with HTML 5, see this link http://www.html5rocks.com/en/tutorials/file/dndfiles/

查看更多
贪生不怕死
3楼-- · 2019-01-07 10:21

I found This simpler yet powerful tutorial which uses the fileReader Object. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

查看更多
\"骚年 ilove
4楼-- · 2019-01-07 10:27

I feel we had a related discussion earlier: How to upload preview image before upload through JavaScript

查看更多
We Are One
5楼-- · 2019-01-07 10:27

Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.

查看更多
Deceive 欺骗
6楼-- · 2019-01-07 10:31

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

查看更多
够拽才男人
7楼-- · 2019-01-07 10:37
登录 后发表回答