html5以及jQuery實現本地圖片上傳前的預覽
阿新 • • 發佈:2019-01-03
淘到好東西了,趕緊記下來。
下面貼程式碼,超級簡單的,jQuery 也是引用了線上資源庫,所以直接拷下來就能運行了
<!DOCTYPE html> <html> <head> <title>HTML5上傳圖片預覽</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://www.codefans.net/ajaxjs/jquery-1.6.2.min.js"></script> </head> <body> <h3>請選擇圖片檔案:JPG/GIF</h3> <form name="form0" id="form0" > <!-- 這裡特別說一下這個 multiple="multiple" 新增上這個之後可以一次選擇多個檔案進行上傳,是 html5 的新屬性--> <input type="file" name="file0" id="file0" multiple="multiple" /><br><img src="" id="img0" > </form> <script> $("#file0").change(function(){ // getObjectURL是自定義的函式,見下面 // this.files[0]代表的是選擇的檔案資源的第一個,因為上面寫了 multiple="multiple" 就表示上傳檔案可能不止一個 // ,但是這裡只讀取第一個 var objUrl = getObjectURL(this.files[0]) ; // 這句程式碼沒什麼作用,刪掉也可以 // console.log("objUrl = "+objUrl) ; if (objUrl) { // 在這裡修改圖片的地址屬性 $("#img0").attr("src", objUrl) ; } }) ; //建立一個可存取到該file的url function getObjectURL(file) { var url = null ; // 下面函式執行的效果是一樣的,只是需要針對不同的瀏覽器執行不同的 js 函式而已 if (window.createObjectURL!=undefined) { // basic url = window.createObjectURL(file) ; } else if (window.URL!=undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file) ; } else if (window.webkitURL!=undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file) ; } return url ; } </script> </body> </html>