【JavaScript小项目】在网页上显示选择的图片
- 2020 年 2 月 13 日
- 筆記
思路分析
- 选用<input type="file">原生组件,实现该组件美化。
- 选用<img src="file">实现图片预览。
代码实现
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>图片预览</title> <script src="js/test.js"> function upload(file) { console.log(file) let img = document.getElementById('img') let formData = new FormData() let temp = file.files[0] console.log(temp) if (temp){ formData.append('file',temp) img.src = window.URL.createObjectURL(temp) } } </script> <style type="text/css"> .myBtn{ padding: 5px 10px; background: rgb(92,184,92); color: white; outline: none; border: none; border-radius: 5px; cursor: pointer; } </style> </head> <body> <input type="file" style="display: none;" id="file" onchange="upload(this)" /> <button class="myBtn" onclick="fileBtn()">上传文件</button> <br /> <img src="" id="img" style="width: 50%"> </body> </html>
效果展示
本来是想部署通过网页上传一个图片到服务器的功能的。
今天只实现了第一步,把图片选择和预览做了。服务器端还要部署接受服务才行。
就这第一步都花费了两个小时,孰能生巧啊。只学不习永远都落实不了。
一番雾语:JavaScript上传图片并预览。