1. 程式人生 > 其它 >js 實現上傳圖片和下載

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