1.js讀取文件javascript
/** * 上傳圖片 * @param file 傳入獲取的文件 * @author wangzhen 2018-09-07 */ function loadImg(file,callback){ //建立讀取文件的對象 var reader = new FileReader(); //建立文件讀取相關的變量 var imgFile; //爲文件讀取成功設置事件 reader.onload=function(e) { // console.log('文件讀取完成'); imgFile = e.target.result; // console.log(imgFile); // $("#imgLicense").attr('src', imgFile); // callback(imgFile); callback(file); }; //正式讀取文件 reader.readAsDataURL(file); }
2.將以base64的圖片url數據轉換爲Blobcss
// -------- 將以base64的圖片url數據轉換爲Blob -------- function convertBase64UrlToBlob(urlData, filetype){ //去掉url的頭,並轉換爲byte var bytes = window.atob(urlData.split(',')[1]); //處理異常,將ascii碼小於0的轉換爲大於0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); var i; for (i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], {type : filetype}); }
3.input獲取html
3.1 html部分java
<div class="file-box"> <input type="file" class="file-btn" @change="uploadImg($event)" readonly="readonly"/> 上傳圖片 </div>
3.2 css部分app
.file-box{ display: inline-block; position: relative; padding: 3px 5px; overflow: hidden; color:#fff; background-color: red; border-radius: 5px; } .file-btn{ position: absolute; width: 100%; height: 100%; top: 0; left: 0; outline: none; background-color: transparent; filter:alpha(opacity=0); -moz-opacity:0; -khtml-opacity: 0; opacity: 0; }
3.3 js部分url
function uploadImg(event){ // console.log(event); var imgFile = event.target.files[0]; //傳遞參數fd var fd = new FormData(); fd.append("file",imgFile); }