最近接到一個需求,需要一個共享文件列表,支持文件的上傳與下載,先貼個效果圖
說重點:
普通類型文件的下載我們可以通過給a標籤添加href和download屬性,便可以實現下載文件了,但是唯獨(不同源)圖片不行!!!
1.首先點擊下載不同源圖片的時候會報跨域的問題,網上找了很多種解決辦法,前端都無法解決這個圖片跨域的問題,最後只能求助後臺,讓後臺把圖片地址轉爲base64位的圖片;
2.在表格中批量下載其他文件的時候,我選擇的是用iframe創建a標籤的方式去下載的,下載圖片由於是base64的圖片,還需要做進一步的處理:
1>批量下載數據的時候,我們在批量選中的方法中循環調用createIFrame方法去下載多個文件或圖片
//批量下載文件
openDownload(){
let that = this;
const triggerDelay = 100;
const removeDelay = 1000;
if(this.selectData.length==0){
that.$message({
message:'Please select the file to download',
type:'warning',
showClose: true,
})
}else{
this.selectData.forEach((item, index)=> {
that.createIFrame(item.fileUrl, index * triggerDelay,
removeDelay,item.fileName,item.id);
that.cancelSelection();
})
}
},
2> 在下載文件的方法中,我們根據後綴判斷,是圖片的就按圖片的方式處理,其他的就按創建iframe的方式處理
//創建iframe下載對應文件
createIFrame (url, triggerDelay, removeDelay,name,id){
let that = this;
let urltype = /\.[^\.]+$/.exec(url)[0];
//下載圖片類型的文件
if(urltype=='.PNG' || urltype=='.png' || urltype =='.jpg'){
that.downloadImg(name,id);
}
//下載其他類型的文件
else{
setTimeout(function (){
//動態添加iframe,設置src,然後刪除
const frame = document.createElement('iframe') //創建a對象
frame.setAttribute('style', 'display: none')
frame.setAttribute('src', url)
frame.setAttribute('id', 'iframeName')
document.body.appendChild(frame)
setTimeout(function(){
const node = document.getElementById('iframeName')
node.parentNode.removeChild(node)
}, removeDelay)
}, triggerDelay)
}
},
3> 圖片格式文件的處理,需要先請求到後臺返回的base64圖片路徑,然後在做處理
downloadImg(name,id){
let that = this;
let url = "resource/downloadFileShare?" +
"id=" + id;
this.$axios.getData(url, function (data, message) {//正常爲null
if(data){
// console.log(data)
const imgUrl = that.prefixBase64 + data;
// 如果瀏覽器支持msSaveOrOpenBlob方法(也就是使用IE瀏覽器的時候),那麼調用該方法
去下載圖片
if (window.navigator.msSaveOrOpenBlob) {
let bstr = atob(imgUrl.split(",")[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let blob = new Blob([u8arr]);
window.navigator.msSaveOrOpenBlob(blob, name + "." + "png");
} else {
// 這裏就按照chrome等新版瀏覽器來處理
let a = document.createElement("a");
a.href = imgUrl;
a.setAttribute("download", name);
a.click();
}
}
})
},
注:該方法可以實現下載圖片到本地文件夾,而不是單單通過瀏覽器打開圖片文件!!!