[英]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.我正在构建一个基本的 social.network 并在注册时用户上传显示图像。 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.
基本上我想显示图像,就像在与表单相同的页面上预览一样,就在他们 select 之后和提交表单之前。
Is this possible?这可能吗?
Here is the complete example for previewing image before it gets upload. 以下是在上传之前预览图像的完整示例。
HTML : 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 : 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. 我找到了这个使用
fileReader
对象的更简单但功能强大的教程 。 It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input 它只是创建一个img元素,并使用fileReader对象将其source属性指定为表单输入的值
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/ 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">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.