js 实现上传图片和下载
上传图片
通过onchange触发文件选择后的方法,然后通过浏览器提供的URL.createObjectURL()方法构建一个本地的blob对象路径
e.target 得到的是input对象
e.target.files[0]. 得到的input选择的第一张图片
html:
<body> <input type="file" value="选择文件" id="file"> <img src="" id="img" alt="暂无" width="50" height="50"> </body> js: <script> let file = document.querySelector("#file"); //查找网页中的id为file的选择器 let img = document.querySelector("#img"); file.onchange = function(e) { console.log(e); //参数 img.src = URL.createObjectURL(e.target.files[0]); } </script>
文件上传和下载
html: <body> <button id="upload">下载</button> <input type="file" value="选择文件" id="file"> <img src="" id="img" alt="暂无" width="50" height="50"> </body> js: <script> let file = document.querySelector("#file"); //表单 let img = document.querySelector("#img"); //图片 let upload = document.querySelector("#upload"); //下载 let body = document.body; let file1 = null; file.onchange = function(e) { console.log(e); file1 = e.target.files[0]; //文件上传 img.src = URL.createObjectURL(e.target.files[0]); //图片上传 } upload.onclick = function() { let a = document.createElement("a"); a.setAttribute("href", URL.createObjectURL(file1)); a.setAttribute("download", file1.name); //file1.name文件的名字 a.click(); } </script>
————————————————
版权声明:本文为CSDN博主「爬楼梯的前端小白」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_57607714/article/details/119430894