vue+axios+elementUI文件上传与下载

Simple_Learn 关注

 0.5 2018.05.30 10:20 字数 209 阅读 15111评论 4喜欢 6

1.文件上传

这里主要介绍一种,elementUI官网 上传组件 http-request 这种属性的使用。

 
图片.png

代码如下:

 <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属性

 
api文件

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

 
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);
}
}
 
图片.png

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("下载附件失败,请联系管理员");
});
}
 
api.js
 
vuex

总之如下:

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文件上传与下载的更多相关文章

  1. vue之element-ui文件上传

    vue之element-ui文件上传 文件上传需求 ​ 对于文件上传,实际项目中我们的需求一般分两种: 对于单个的文件上传,比如拖动上传个图片之类的,或者是文件. 和表单一起实现上传(这种情况一般都是 ...

  2. vue中的文件上传和下载

    文件上传 vue中的文件上传主要分为两步:前台获取到文件和提交到后台 获取文件 前台获取文件,主要是采用input框来实现 <el-dialog :title="addName&quo ...

  3. vue.js+elementUI文件上传、文件导入、文件下载

    1.文件下载 <el-button plain @click ="exportVmExcel()" size='mini' icon="el-icon-downlo ...

  4. JavaWeb:实现文件上传与下载

    JavaWeb:实现文件上传与下载 文件上传前端处理 本模块使用到的前端Ajax库为Axio,其地址为GitHub官网. 关于文件上传 上传文件就是把客户端的文件发送给服务器端. 在常见情况(不包含文 ...

  5. koa2基于stream(流)进行文件上传和下载

    阅读目录 一:上传文件(包括单个文件或多个文件上传) 二:下载文件 回到顶部 一:上传文件(包括单个文件或多个文件上传) 在之前一篇文章,我们了解到nodejs中的流的概念,也了解到了使用流的优点,具 ...

  6. 精讲响应式WebClient第4篇-文件上传与下载

    本文是精讲响应式WebClient第4篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...

  7. java web学习总结(二十四) -------------------Servlet文件上传和下载的实现

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  8. (转载)JavaWeb学习总结(五十)——文件上传和下载

    源地址:http://www.cnblogs.com/xdp-gacl/p/4200090.html 在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传 ...

  9. JavaWeb学习总结,文件上传和下载

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

随机推荐

  1. Winscp隧道实现-跳板机/跨机连接

    隧道用的是公网ip,登陆用的是私网ip 一张图应该就能看懂,后续用到新的功能继续编辑

  2. 三种TCP协议聊天室实现

    一 概述 使用Java的IO实现聊天室 使用Java的NIO实现聊天室 使用Netty实现聊天室 二 IO聊天室 1 服务器 public class IOServer { public static ...

  3. internal关键字

    internal修饰符可以用于类型或成员,使用该修饰符声明的类型或成员只能在同一程集内访问,接口的成员不能使用internal修饰符. 就是使用internal的类只能在同一个项目中使用,不能在别的项 ...

  4. sys.dm_exec_query_stats的total_worker_time的单位是微秒还是毫秒

    该视图sys.dm_exec_query_stats存放的就是当前所有执行计划的详细信息,比如某条执行计划共占CPU多少等等.因为该视图对编译次数.占用CPU资源总量.执行次数等都进行了详细的记录,所 ...

  5. cli create ssl certkey

    cli create ssl certkey ############################### # 创建CA密钥 create ssl rsakey bwsrv-root.key -ex ...

  6. HotSpot JVM目录

    一.知识结构整理 jvm体系大体分四大块: 类的加载机制 jvm内存结构 GC算法 垃圾回收 GC分析 命令调优 二.运行时JVM结构组成及作用 http://www.cnblogs.com/imxi ...

  7. Servlet实现图片读取显示

    1.导入jar包:commons-io-1.4.jar 2.index.jsp: <%@ page language="java" import="java.uti ...

  8. LINUX档案权限

    一.ls命令显示目录详细信息 列表显示目录内容 : ls drwxr-xr-x.  4 root   root       4096 Jun 26 02:07 acpi -rw-r--r--.  1 ...

  9. c# System.Enum的方法

  10. Django中使用xadmin作为后台管理页面

    xadmin后台管理 安装:luffy虚拟环境下 # >: pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2 ...