js关于base64文件的处理以及下载
- 获取完整base64地址
- base64转Blob
- base64转File
- 下载base64文件
- 下载图片
- 下载普通文件
- 批量下载文件并导出为zip
获取完整base64地址
function downladBase64(item) {
APINAME().then((res) => {
let base64 = getBase64Type(res.data.fileType) + res.data.data
console.log('拼接完整的base64', base64)
downloadFileByBase64(base64, res.data.fileName)
})
}
function getBase64Type(type) {
switch (type) {
case 'txt':
return 'data:text/plain;base64,'
case 'doc':
return 'data:application/msword;base64,'
case 'docx':
return 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,'
case 'xls':
return 'data:application/vnd.ms-excel;base64,'
case 'xlsx':
return 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'
case 'pdf':
return 'data:application/pdf;base64,'
case 'pptx':
return 'data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,'
case 'ppt':
return 'data:application/vnd.ms-powerpoint;base64,'
case 'png':
return 'data:image/png;base64,'
case 'jpg':
return 'data:image/jpeg;base64,'
case 'gif':
return 'data:image/gif;base64,'
case 'svg':
return 'data:image/svg+xml;base64,'
case 'ico':
return 'data:image/x-icon;base64,'
case 'bmp':
return 'data:image/bmp;base64,'
}
}
base64转Blob
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}
base64转File
export default async function base64ImgtoFile(dataurl, filename = 'file') {
try {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const suffix = mime.split('/')[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
} catch (err) {
return Promise.reject(err);
}
}
下载base64文件
function downloadFileByBase64(base64, fileName) {
var myBlob = dataURLtoBlob(base64)
var myUrl = URL.createObjectURL(myBlob)
downloadFile(myUrl, fileName)
}
function downloadFile(url, name = "What's the fuvk") {
console.log('url==', url)
var a = document.createElement("a")
a.setAttribute("href", url)
a.setAttribute("download", name)
a.setAttribute("target", "_blank")
let clickEvent = document.createEvent("MouseEvents")
clickEvent.initEvent("click", true, true)
a.dispatchEvent(clickEvent)
}
export default downloadFileByBase64
下载图片
export const downloadImage = (imgsrc, name) => {
var image = new Image()
image.setAttribute('crossOrigin', 'anonymous')
image.onload = function() {
var canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
var context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
var url = canvas.toDataURL('image/png')
var a = document.createElement('a')
var event = new MouseEvent('click')
a.download = name || 'photo'
a.href = url
a.dispatchEvent(event)
}
image.src = imgsrc
}
下载普通文件
export const downloadFile = (path, name = 'name.jpg') => {
const download = (href) => {
const a = document.createElement('a')
a.style.display = 'none'
a.href = href
a.download = name
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
if (isIE()) {
download(path)
} else {
const xhr = new XMLHttpRequest()
xhr.open('get', path)
xhr.responseType = 'blob'
xhr.send()
xhr.onload = (e) => {
const { status, response } = e.target
if (status === 200 || status === 304) {
const fileReader = new FileReader()
fileReader.readAsDataURL(response)
fileReader.onload = (ev) => {
download(ev.target.result)
}
}
}
}
}
export function isIE() {
return /msie|trident/.test(window.navigator.userAgent.toLowerCase())
}
批量下载文件并导出为zip
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import axios from 'axios'
function getFile(url) {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url,
responseType: 'arraybuffer'
}).then(data => {
resolve(data.data)
}).catch(error => {
console.log(error, url, 'getfile-err')
resolve('')
})
})
}
function batchDownZip(files, zipName, callback) {
const data = files
const zip = new JSZip()
const cache = {}
const promises = []
data.forEach(item => {
const promise = getFile(item.url).then(result_file => {
let file_name = item.name
let lastIndex = file_name.lastIndexOf('/')
console.log(result_file, file_name, lastIndex, 'result_file111')
if (lastIndex > -1) {
file_name = file_name.slice(lastIndex + 1)
}
console.log(result_file, file_name, lastIndex, 'result_file222')
zip.file(file_name, result_file, { binary: true })
cache[file_name] = data
})
promises.push(promise)
})
Promise.all(promises).then(() => {
zip.generateAsync({ type: 'blob' }).then(content => {
FileSaver.saveAs(content, zipName)
callback && callback()
})
})
}
export default batchDownZip