HTML input type=file,提交表单前获取图片

问题描述 投票:0回答:6

我正在建立一个基本的社交网络,在注册时用户上传一张显示图像。 基本上我想显示图像,就像在与表单相同的页面上预览一样,就在他们选择它之后和提交表单之前。

这可能吗?

javascript html forms file-io
6个回答
74
投票

这是上传前预览图像的完整示例。

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]);
  }
}

62
投票

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


18
投票

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


5
投票

感觉我们之前有过相关的讨论:How to upload preview image before upload through JavaScript


2
投票

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


0
投票
URL.createObjectURL(e.dataTransfer.files[0]);

这段代码对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.