<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
js讀取檔案的操作是什麼樣的呢?一起來看下吧:
1、js讀取檔案;
/** * 上傳圖片 * @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數據轉換爲Blob;
// -------- 將以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獲取:
(1)html部分;
上傳圖片
(2)css部分;
.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)js部分
function uploadImg(event){ // console.log(event); var imgFile = event.target.files[0]; //傳遞參數fd var fd = new FormData(); fd.append("file",imgFile); }