1. 程式人生 > 實用技巧 >input[ type="file"]上傳檔案問題

input[ type="file"]上傳檔案問題

input標籤中的type屬性支援很多不同的型別如text,password,money等,在很早之前對上傳檔案的功能做過一次嘗試,後來給忘記了,前幾天被難為了一次翻翻找找找到了之前寫過的一個小demo放上來免得又忘掉。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style type="text/css">
            *{
                margin
: 0; padding: 0; } ul{ display: flex; list-style: none; } li{ position: relative; margin: 10px; height: 200px; } .cover{
position: absolute; height: 100%; width: 100%; background: #111; opacity: 0.5; bottom: 0; } span{ display: inline-block; width: 180px; font-size
: 150px; line-height: 180px; text-align: center; border: 10px saddlebrown solid; } #add{ margin: 10px; position: relative; } input{ position: absolute; display: inline-block; width: 200px; height: 200px; top: 0; left: 0; opacity: 0; } img{ height: 200px; } #box{ } #body{ display: flex; } </style> </head> <body> <div id="body"> <ul id="box"> </ul> <div id="add"> <span> + </span> <input type="file" name="" id="fs" multiple="multiple" value="" /> </div> </div> <script type="text/javascript"> fs.onchange=function (e) { let info=e.target.files let peg=/^image\// for (let i=0 ;i<info.length;i++) { if (peg.test(info[i].type)==false){ alert("不是圖片形式檔案無法上傳") continue } let readfs=new FileReader() readfs.readAsDataURL(info[i]) readfs.onload=function(){ let img = new Image img.src=readfs.result let li=document.createElement("li") let coverDiv=document.createElement("div") coverDiv.setAttribute("class","cover") li.appendChild(coverDiv) li.appendChild(img) box.appendChild(li) let xhr=new XMLHttpRequest xhr.open("POST","/upload",true) xhr.upload.onprogress=function (e) { var b=(e.loaded/e.total)*100 coverDiv.style.height=(100-b)+"%" li.style.border="cornflowerblue solid 2px" } xhr.onload=function () { if (xhr.status==200) { console.log(xhr.responseText) } } let data =new FormData data.append("abc",info[i]) xhr.send(data) } } } </script> </body> </html>

頁面效果也一起放上來吧