vue实现Excel文件的上传与下载功能的两种方式

2020-06-14 06:02:01易采站长站整理

_this.Refresh();
_this.tableData = result.uploadErrors;
_this.successCount = result.successCount;
_this.innerVisible = true;
} else if (result.errorCount == 0 && result.successCount == 0) {
_this.$message({
message: `上传文件中数据为空`,
type: "error"
});
}
}
})
.catch(function(error) {
console.log(error);
});
},

这是上传文件的调用方法。

2.模板下载

关于模板下载,之前没有考虑到IE10浏览器的兼容问题,导致在IE10下文件没法下载,后来百度后找到了解决办法。


downloadFile(name) {
let requestConfig = {
headers: {
"Content-Type": "application/json;application/octet-stream"
}
};
AjaxHelper.post(this.downLoadUrl, requestConfig, {
responseType: "blob"
}).then(res => {
// 处理返回的文件流
const content = res.data;
const blob = new Blob([content]);
var date =
new Date().getFullYear() +
"" +
(new Date().getMonth() + 1) +
"" +
new Date().getDate();
const fileName = date + name + ".xlsx";
if ("download" in document.createElement("a")) {
// 非IE下载
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName);
}
});
},

  前端的处理就结束了。

3.后端对于文件上传和下载的处理

文件上传


public UploadResult UploadFiles(IFormFile file, Guid brandId)
{
try
{
UploadResult uploadResult = new UploadResult();
if (file == null)
{
throw new UserFriendlyException(501, "上传的文件为空,请重新上传");
}
string filename = Path.GetFileName(file.FileName);
string fileEx = Path.GetExtension(filename);//获取上传文件的扩展名
string NoFileName = Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
string FileType = ".xls,.xlsx";//定义上传文件的类型字符串
if (!FileType.Contains(fileEx))
{
throw new UserFriendlyException(501, "无效的文件类型,只支持.xls和.xlsx文件");
}
//源数据
MemoryStream msSource = new MemoryStream();