input上傳檔案的各種轉換操作(一)
阿新 • • 發佈:2021-07-08
檔案物件---->base64
base64 ---> blob
blob --- > flie
本地json檔案 ---> 讀取成json
指定url瀏覽器下載檔案
import { getBase64, dataURLtoBlobs, blobToFile } from '@/utils/util.js'
本地json檔案 ---> 讀取成json
geJsonData (file) { const __this = this var reader = new FileReader()// 新建一個FileReader reader.readAsText(file, 'UTF-8')//讀取檔案 reader.onload = function (evt) { // 讀取完檔案之後會回來這裡 var fileString = evt.target.result // 讀取檔案內容 const jsonObj = JSON.parse(fileString) __this.actData[file.name] = jsonObj.animations } },
檔案物件---->base64
// util.js export function getBase64 (img, callback) { console.log('getBase64', img) const reader = new FileReader() reader.addEventListener('load', (e) => { callback(reader.result) }) reader.readAsDataURL(img) } handleChange (info) { // 得到blob格式資料 上傳 getBase64(item.originFileObj, (result) => { __this.fileBlobObj[item.name] = dataURLtoBlobs(result) __this.postImage(item) }) }
base64 ---> blob
// 將base64轉換為blob export function dataURLtoBlobs (dataurl) { var arr = dataurl.split(',') var mime = arr[0].match(/:(.*?);/)[1] var bstr = atob(arr[1]) var n = bstr.length var u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([u8arr], { type: mime }) }
blob --- > flie
// 將blob轉換為file export function blobToFile (theBlob, fileName) { theBlob.lastModifiedDate = new Date() theBlob.name = fileName return theBlob }
4、下載
function openDownloadDialog (url, saveName) { if (typeof url === 'object' && url instanceof Blob) { url = URL.createObjectURL(url) } var aLink = document.createElement('a') aLink.href = url aLink.download = saveName || '' var event if (window.MouseEvent) event = new MouseEvent('click') else { event = document.createEvent('MouseEvents') event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null) } aLink.dispatchEvent(event) } openDownloadDialog(sheet2blob(sheet), xmlName + '.xlsx')
5、