[英]File input : Chrome is not checking if file still exist before submitting form
[英]HTML input type=file, get the image before submitting the form
我正在构建一个基本的 social.network 并在注册时用户上传显示图像。 基本上我想显示图像,就像在与表单相同的页面上预览一样,就在他们 select 之后和提交表单之前。
这可能吗?
以下是在上传之前预览图像的完整示例。
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]);
}
}
我找到了这个使用fileReader
对象的更简单但功能强大的教程 。 它只是创建一个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/
我觉得我们之前有过相关的讨论: 如何在通过JavaScript上传之前上传预览图像
图像在从任何服务器提供之前无法显示。 因此您需要将图像上传到服务器以显示其预览。
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.