简体   繁体   中英

HTML input type=file, get the image before submitting the form

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?

Here is the complete example for previewing image before it gets upload.

HTML :

<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>

JavaScript :

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#blah')
        .attr('src', e.target.result)
        .width(150)
        .height(200);
    };
    reader.readAsDataURL(input.files[0]);
  }
}

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..."> 

这可以通过HTML 5轻松完成,请参阅此链接http://www.html5rocks.com/en/tutorials/file/dndfiles/

nice open source file uploader

http://blueimp.github.com/jQuery-File-Upload/

我觉得我们之前有过相关的讨论: 如何在通过JavaScript上传之前上传预览图像

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.

 const inputImg = document.getElementById('imgInput') const img = document.getElementById('img') function getImg(event){ const file = event.target.files[0]; // 0 = get the first file // console.log(file); let url = window.URL.createObjectURL(file); // console.log(url) img.src = url } inputImg?.addEventListener('change', getImg)
 <img id='img' alt="images"> <input id="imgInput" accept="image/*" type="file">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM