最近在項目時,需要獲取用戶的上傳文件的路徑,便寫了一個demo:
<body> <input type="file" name="" value=""> <script> var input = document.getElementsByTagName("input")[0]; console.log(input); input.onchange = function () { var that = this; console.log(that.files[0]); var src = window.URL.createObjectURL(that.files[0]) console.log(src); var img = document.createElement("img"); img.style.width = "200px"; img.src = src; document.body.appendChild(img); } </script>
效果及結果如下:
通過input[type=file]上傳圖片獲取圖片的尺寸:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form id="form"> <!-- 1.給input標簽添加一個onchange事件:一旦選擇文件發生變化則會觸發 目的:獲取選擇圖片的原始數據 --> <input type="file" id="exampleInputFile" name="icon" onchange=uploadImg(this)>
<!-- 2.用一個img標簽來接收文件數據 目的:(1)先接收文件數據 (2)通過offsetHeight屬性獲取寬高 --> <img src="" alt="" id="11111"> <p>請上傳圖片.</p> </form> </body> <script> //選擇圖片,馬上預覽 function uploadImg(obj) { //1.讀取文件詳細信息 var file = obj.files[0]; console.log(obj); console.log(file); //2.使用FileReader讀取文件信息 var reader = new FileReader(); //4.監聽讀取文件過程方法,異步過程 reader.onloadstart = function (e) { console.log("開始讀取...."); } reader.onprogress = function (e) { console.log("正在讀取中...."); } reader.onabort = function (e) { console.log("中斷讀取...."); } reader.onerror = function (e) { console.log("讀取異常...."); } reader.onload = function (e) { console.log("成功讀取...."); console.log(this.reault); //或者 img.src = this.result; //e.target == this var img = document.getElementById("11111"); //將解析的base64字符串賦值給img標簽 img.src = e.target.result; //5.這里需要異步獲取,避免線程延遲 setTimeout(function(){ window.alert('高度' + img.offsetHeight + '寬度' + img.offsetWidth); },1000); }
//3.開始讀取 reader.readAsDataURL(file) } </script> </html>