话不多说直接上前端代码:
downFile(index, rows){ //index 表示选的第几行 rows表示整个列表 rows[index]表示当前行数据
var curRow = rows[index];
var fileName = curRow.fileName;
var physicalPath = curRow.physicalPath; // 文件路径
if (undefined == fileName) {
return;
}
if ('' == fileName) {
return;
}
var suffix = fileName.substring(fileName.lastIndexOf(".") + 1)
var blobType = '';
if (suffix.toLocaleUpperCase() == 'DOCX') {
blobType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8';
} else if (suffix.toLocaleUpperCase() == 'DOC') {
blobType = 'application/msword';
} else if (suffix.toLocaleUpperCase() == 'XLSX') {
blobType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
} else if (suffix.toLocaleUpperCase() == 'XLS') {
blobType = 'application/vnd.ms-excel';
} else if (suffix.toLocaleUpperCase() == 'PDF') {
blobType = 'application/pdf';
} else if (suffix.toLocaleUpperCase() == 'PNG') {
blobType = 'image/png';
} else if (suffix.toLocaleUpperCase() == 'JPEG') {
blobType = 'image/jpeg';
} else if (suffix.toLocaleUpperCase() == 'JPG') {
blobType = 'image/jpeg';
}else{
this.$message.error('只能下载:DOCX、DOC、XLSX、XLS、PDF、PNG、JPEG、JPG类型的文件!')
return
}
request({
url: this.GLOBAL.PROJECT_ID + '/api/file/downFile?physicalPath='+physicalPath,
method: 'get',
responseType: 'arraybuffer'
}).then(response => {
var blob = new Blob([response], {type: blobType});
var href = URL.createObjectURL(blob);
var downloadElement = document.createElement('a');
downloadElement.href = href;
downloadElement.download = fileName; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
}).catch(function(reason) {
console.log('catch:', reason);
});
}
后端代码: