html:
<input id="img" type="file"> // 上传图片
<img id="pic" src=""> // 预览
js:
<script src="jquery.js"></script> // 引入jquery
<script>
$(function(){
$("#img").change(function(e){
let img = e.currentTarget.files[0]; // 当前图片文件对象
// let img = $("#img")[0].files[0];
const windowURL = window.URL || window.webkitURL;
// window.URL.createObjectURL 会根据传入的参数创建一个指向该参数对象的URL
let imgSrc = windowURL.createObjectURL(img); // 生成预览地址
$("#pic").attr('src',imgSrc);
});
let sendData = new FormData();
sendData.append('file', $("#img")[0].files[0]); // 图片对象
});
</script>
本文介绍了如何使用HTML和JavaScript实现图片文件的上传,并通过window.URL.createObjectURL实现实时预览。涉及了HTML input元素、jQuery的选择器和FormData对象的应用。
858

被折叠的 条评论
为什么被折叠?



