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中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
随机推荐
- Pywinauto使用方法
3 Pywinauto使用 连接为 http://pywinauto.github.io/ 3.1 关联到一个应用,用以下方法: ? start_(path) connect_(handle or p ...
- Redis主从及Cluster区别及注意事项
https://yq.aliyun.com/articles/647342 https://blog.csdn.net/biren_wang/article/details/78117392 http ...
- web&http协议&django初识
1.什么是web应用 Web应用程序是一种可以通过Web访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要再安装其他软件. 应用程序有两种模式C/S.B/S ...
- codeforce 839d.winter is here
题意:如果一个子序列的GCD为1,那么这个子序列的价值为0,否则子序列价值为子序列长度*子序列GCD 给出n个数,求这n个数所有子序列的价值和 题解:首先得想到去处理量比较少的数据的贡献,这里处理每个 ...
- hdu 1285 拓扑
确定比赛名次 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Subm ...
- (八)SpringBoot之freeMarker基本使用
一.案例 1.1 pom.xml <dependencies> <!-- 除去logback支持 --> <dependency> <groupId>o ...
- MySQL存储的字段是不区分大小写的,你知道吗?
做一个积极的人 编码.改bug.提升自己 我有一个乐园,面向编程,春暖花开! 00 简单回顾 之前写过一篇关于mysql 对表大小写敏感的问题,其实在mysql中字段存储的内容是不区分大小写的,本篇进 ...
- 一、eureka服务端自动配置
所有文章 https://www.cnblogs.com/lay2017/p/11908715.html 正文 @EnableEurekaServer开关 eureka是一个c/s架构的服务治理框架, ...
- [Vuex系列] - Mutation的具体用法
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation.Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 ...
- Python 遍历文件夹清理磁盘案例
import os suffix_name_list = [".pdb", ".ilk"] def find_file(path): # 遍历文件夹 for i ...