vue+axios+elementUI文件上传与下载
vue+axios+elementUI文件上传与下载
1.文件上传
这里主要介绍一种,elementUI官网 上传组件 http-request 这种属性的使用。

代码如下:
<el-upload class="uploadfile" action="" :http-request='uploadFileMethod' :show-file-list="false" multiple>
<el-button class="custom-btn" size="small">上传</el-button>
</el-upload>
uploadFileMethod方法如下:
uploadFileMethod(param) {
const id = this.currentRowObject.id;
let fileObject = param.file;
let formData = new FormData();
formData.append("file", fileObject);
this.$store
.dispatch("UploadFile", { formData: formData, id: id })
.then(response => {
if (Array.isArray(response)) {
if (response) {
this.$message({
showClose: true,
message: "上传成功。",
type: "success"
});
this.getFileList(id);
}
} else {
this.$message.error(response.message);
}
console.log("response==", response);
})
.catch(message => {
console.log("message======================", message);
this.$message.error("上传失败,请联系管理员");
});
},
这里需要设置header属性

这里是因为封装了axios方法,还使用了vuex。

可将ajax直接替换成axios就好,具体可参见{axios}如下:
axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
这里formData就是要向后台传的数据。
2.文件下载
2.1 一种是url式的下载,相当于get请求下载
后台提供一个url。前端a标签href设置上就好。
//带文件名的单个文件下载
@RequestMapping(path = "/downloadwithname/{id}", method = RequestMethod.GET)
public void downloadWithFileName(@PathVariable(name = "id") String strId,
HttpServletResponse response) {
Long id = Utils.stringTransToLong(strId);
//设置Content-Disposition
String fileName = fileService.getFileName(id);
InputStream inputStream = fileService.download(id);
OutputStream outputStream = null;
try {
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
response.flushBuffer();
} catch (IOException e) {
logger.error(e.getMessage(), e);
throw new BizBaseException("server error.");
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}

2.2一种是post请求下载 (以流的形式下载文件)
downloadFile() {
const rowId = this.currentRowObject.id;
const rowName = this.currentRowObject.name;
let params = {
ids: this.checkedFileId,
id: rowId
};
this.$store
.dispatch("DownloadFile", params)
.then(res => {
if (res) {
console.log("download===",res);
const content = res.data;
const blob = new Blob([content]);
const fileName = `${rowName}.zip`;
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);
}
}
})
.catch(() => {
this.$message.error("下载附件失败,请联系管理员");
});
}


总之如下:
axios.post('/download', data, {responseType:'blob' })
后端这里需要设置header:
response.setContentType("application/octet-stream");
// 以流的形式下载文件
try {
InputStream fis = new BufferedInputStream(new FileInputStream(zipFilePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();// 清空response
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));// 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//删除临时压缩文件
try {
File f = new File(zipFilePath);
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
就先简单介绍这里,如有问题可以留言讨论学习。
vue+axios+elementUI文件上传与下载的更多相关文章
- vue之element-ui文件上传
vue之element-ui文件上传 文件上传需求 对于文件上传,实际项目中我们的需求一般分两种: 对于单个的文件上传,比如拖动上传个图片之类的,或者是文件. 和表单一起实现上传(这种情况一般都是 ...
- vue中的文件上传和下载
文件上传 vue中的文件上传主要分为两步:前台获取到文件和提交到后台 获取文件 前台获取文件,主要是采用input框来实现 <el-dialog :title="addName&quo ...
- vue.js+elementUI文件上传、文件导入、文件下载
1.文件下载 <el-button plain @click ="exportVmExcel()" size='mini' icon="el-icon-downlo ...
- JavaWeb:实现文件上传与下载
JavaWeb:实现文件上传与下载 文件上传前端处理 本模块使用到的前端Ajax库为Axio,其地址为GitHub官网. 关于文件上传 上传文件就是把客户端的文件发送给服务器端. 在常见情况(不包含文 ...
- koa2基于stream(流)进行文件上传和下载
阅读目录 一:上传文件(包括单个文件或多个文件上传) 二:下载文件 回到顶部 一:上传文件(包括单个文件或多个文件上传) 在之前一篇文章,我们了解到nodejs中的流的概念,也了解到了使用流的优点,具 ...
- 精讲响应式WebClient第4篇-文件上传与下载
本文是精讲响应式WebClient第4篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...
- java web学习总结(二十四) -------------------Servlet文件上传和下载的实现
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- (转载)JavaWeb学习总结(五十)——文件上传和下载
源地址:http://www.cnblogs.com/xdp-gacl/p/4200090.html 在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传 ...
- JavaWeb学习总结,文件上传和下载
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
随机推荐
- IBM Security AppScan Standard使用方法
一.常规配置Appscan (安全自动化测试工具) Appscan是web应用程序渗透测试舞台上使用最广泛的工具之一.它是一个桌面应用程序,它有助于专业安全人员进行Web应用程序自动化脆弱性评估.本文 ...
- js 根据 数组条件 简单查询的方法临时保存
let array = [{ date: '2016-05-02', name: 'Ethan', status: 'success', total: '81' }, { date: '2016-05 ...
- SVM的概率输出(Platt scaling)
SVM的概率输出(Platt scaling) 2015-10-22 10:38:19 闲渔Love吉他 阅读数 8121 文章标签: Platt Scaling Calibr 更多 分类专栏: 计算 ...
- django 浅谈索引(转)
https://blog.csdn.net/qq_37049050/article/details/80749381
- 怎样通过混入(Mixin)实现多继承
js不提供现成的多重继承的方法, 但可以通过Object.assign()来手动实现: function Father1(name){ this.name = name; } function Fat ...
- java实现工程配置文件敏感字段加解密
以下引自他人博客: 1. 需求背景我们在开发应用时,需要连接数据库,一般把数据库信息放在一个属性配置文件中,比如***.properties,具体的内容 #mysql的配置文件jdbc.url=jdb ...
- [异步请求]ajax、axios、fetch之间的详细区别以及优缺点
1.jQuery ajax $.ajax({ type: 'POST', url: url, data: data, dataType: dataType, success: function () ...
- (四)自定义多个Realm以及Authenticator与AuthenticationStrategy
多Realm配置 #声明一个realm myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1 myRealm2=com.githu ...
- Nginx实现同一端口HTTP跳转HTTPS
小目标:在只监听一个端口的情况下,将http访问跳转为https. 一般情况下http协议使用80端口,https协议443端口.要实现http强制转https是非常简单的事,随便都可以找到很多方案. ...
- Vs2017 FrameWork EF Mysql 控制台应用
1 运行环境 vs2017 Net FromWork 4.6.2 手动版 没有 ado.net 实体数据模型 2 NuGet MySql.Data.Entity 6.10.9, MySq ...