项目结构

  • 后端

  • 前端

效果演示

  • 上传文件

  • 下载文件

Code

后端代码

  • 跨域
/**
* 跨域配置
* @author Louis
* @date Jan 12, 2019
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer { @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径
.allowedOrigins("*") // 允许跨域访问的源
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // 允许请求方法
.maxAge(168000) // 预检间隔时间
.allowedHeaders("*") // 允许头部设置
.allowCredentials(true); // 是否发送cookie
}
}
  • 上传文件
    /**
* todo 文件上传
* @param response
* @param file
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public R uploadFile(HttpServletResponse response, MultipartFile file) {
response.setContentType("text/html;charset=UTF-8");
// 设置大小
long maxSize = (long) (1000 * 1024 * 1024);
Map<String, Object> result = new HashMap<String, Object>();
String fileName = file.getOriginalFilename();
if (file.getSize() > maxSize) {
result.put("result", "fail");
result.put("msg", "不能查过100MB");
logger.warn("文件大小超过100MB");
} else {
try {
Date date = new Date();
String relativeDir = getRelativeDir(date);
File fileDir = new File(filePath + relativeDir);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
//新的文件名
String newName = CommonUtil.format(date, "HHmmssSSS") +
Math.round(Math.random() * 8999 + 1000) +
fileName.substring(fileName.lastIndexOf("."));
logger.info("文件存储路径:"+filePath + relativeDir + newName);
file.transferTo(new File(filePath + relativeDir + newName));
// 以下可以进行业务逻辑操作 插入数据库等操作
this.sysFileService.save(new SysFile(fileName,relativeDir + newName,file.getSize(),file.getContentType()));
result.put("result", "success");
result.put("data", relativeDir+newName);
result.put("msg", "上传成功");
logger.info("上传成功");
} catch (Exception e) {
result.put("result", "fail");
result.put("msg", "上传失败");
logger.error(e.toString());
}
}
return success(result);
}
  • 下载文件
    /**
* todo 下载文件
* @param response
* @param fileId
*/
@GetMapping("downLoadFile")
public void downLoadFile(HttpServletResponse response, Integer fileId, HttpServletRequest request) {
response.setHeader("Content-Type", "application/octet-stream");
SysFile sysFile = this.sysFileService.getById(fileId);
OutputStream out = null;
try {
File file = new File(filePath + sysFile.getAbsolutepath());
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(sysFile.getFileName(), "UTF-8"));
FileInputStream fin = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fin.read(data);
fin.close();
out = response.getOutputStream();
out.write(data);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

前端代码

  • 页面代码
<template>
<div>
<el-row>
<el-col :span="24">
<el-card class="box-card">
<el-row style="float: left;margin-top: 10px;margin-bottom: 10px ">
<el-col :span="24">
<el-button type="primary" @click="dialogVisible=true">上传</el-button>
</el-col>
</el-row>
<el-table
stripe
highlight-current-row
border
:data="fileDataList"
style="width: 100%">
<el-table-column
prop="fileName"
label="文件名"
align="center"
width="200">
</el-table-column>
<el-table-column
prop="fileSize"
label="文件大小"
align="center"
width="180">
</el-table-column>
<el-table-column
prop="fileTime"
align="center"
label="上传时间">
</el-table-column>
<el-table-column
align="center"
label="操作">
<template slot-scope="scope">
<el-button @click="downLoad(scope.row)" type="text">下载</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
</el-col>
</el-row>
<el-dialog
title="文件上传"
:visible.sync="dialogVisible"
center
width="30%">
<div style="text-align: center">
<el-upload
action
class="upload-demo"
drag
:on-change="fileChange"
:auto-upload="false"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div> <span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="httpRequest">确 定</el-button>
</span>
</el-dialog>
</div> </template> <script>
export default {
name: 'file',
data() {
return {
form: {
fileName: '',
current: 1,
size: 10
},
fileDataList: [],
dialogVisible: false,
file: ''
}
},
methods: {
// 下载文件
downLoad(row) {
this.$http.get(
'/sysFile/downLoadFile',
{params: {fileId: row.fileId}},
{responseType: "blob"}
).then((res) => {
let url = window.URL.createObjectURL(new Blob([res.data]));
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", row.fileName); //指定下载后的文件名,防跳转
document.body.appendChild(link);
link.click();
// 释放内存
window.URL.revokeObjectURL(link.href)
}).catch(function (error) {
console.log(error);
});
},
// 加载文件
async getFileList() {
this.$http.get('/sysFile/selectAll', {params: this.query}).then((res) => {
if (res.data.code == 0) {
this.fileDataList = res.data.data.records;
// this.total = res.data.data.total;
}
}).catch(function (error) {
console.log(error);
});
},
// 上传文件
httpRequest() {
if (this.file == null) {
this.$message.warning('请选择需要上传的文件');
return false;
}
let params = new FormData();
params.append('file', this.file);
let config = {
headers: {'Content-Type': 'multipart/form-data'}
};
this.$http.post('/sysFile/uploadFile', params, config).then((res) => {
if (res.data.code == 0 || res.data.data.result == 'success') {
this.$message.success('文件上传成功');
this.dialogVisible = false;
this.file = '';
this.getFileList();
}
}).catch(function (error) {
console.log(error);
}); },
fileChange(file, fileList) {
this.file = file.raw;
},
},
created() {
this.getFileList();
}
}
</script>
<style scoped>
</style>

注:

前端下载,不建议使用超链接方式

比如这种的,不信可以试试,你就知道为什么了!

 function downloadExcel() {
window.location.href = "/tUserHyRights/downloadUsersUrl";
}

个人觉得使用:对后端发的post请求,使用blob格式

Vue-Element UI 文件上传与下载的更多相关文章

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

    vue+axios+elementUI文件上传与下载 Simple_Learn 关注  0.5 2018.05.30 10:20 字数 209 阅读 15111评论 4喜欢 6 1.文件上传 这里主要 ...

  2. vue+element ui 的上传文件使用组件

    前言:工作中用到 vue+element ui 的前端框架,使用到上传文件,则想着封装为组件,达到复用,可扩展.转载请注明出处:https://www.cnblogs.com/yuxiaole/p/9 ...

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

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

  4. Selenium常用API用法示例集----下拉框、文本域及富文本框、弹窗、JS、frame、文件上传和下载

    元素识别方法.一组元素定位.鼠标操作.多窗口处理.下拉框.文本域及富文本框.弹窗.JS.frame.文件上传和下载 元素识别方法: driver.find_element_by_id() driver ...

  5. 封装Vue Element的upload上传组件

    本来昨天就想分享封装的这个upload组件,结果刚写了两句话,就被边上的同事给偷窥上了,于是在我全神贯注地写分享的时候他就神不知鬼不觉地突然移动到我身边,腆着脸问我在干啥呢.卧槽你妈,当场就把我吓了一 ...

  6. 2014-07-23 利用ASP.NET自带控件实现单文件上传与下载

    效果图 上传文件页面: 下载文件页面:  1.母版页site.Master <%@ Master Language="C#" AutoEventWireup="tr ...

  7. 0062 Spring MVC的文件上传与下载--MultipartFile--ResponseEntity

    文件上传功能在网页中见的太多了,比如上传照片作为头像.上传Excel文档导入数据等 先写个上传文件的html <!DOCTYPE html> <html> <head&g ...

  8. C# 之 FTPserver中文件上传与下载(二)

            通过上一篇博客<C# 之 FTPserver中文件上传与下载(一)>,我们已经创建好了一个FTPserver,而且该server须要username和password的验证 ...

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

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

  10. 全网最简单的大文件上传与下载代码实现(React+Go)

    前言 前段时间我需要实现大文件上传的需求,在网上查找了很多资料,并且也发现已经有很多优秀的博客讲了大文件上传下载这个功能. 我的项目是个比较简单的项目,并没有采用特别复杂的实现方式,所以我这篇文章的目 ...

随机推荐

  1. 文盘Rust -- 用Tokio实现简易任务池

    作者:京东科技 贾世闻 Tokio 无疑是 Rust 世界中最优秀的异步Runtime实现.非阻塞的特性带来了优异的性能,但是在实际的开发中我们往往需要在某些情况下阻塞任务来实现某些功能. 我们看看下 ...

  2. 安装Zookeeper和Kafka集群

    安装Zookeeper和Kafka集群 本文介绍如何安装Zookeeper和Kafka集群.为了方便,介绍的是在一台服务器上的安装,实际应该安装在多台服务器上,但步骤是一样的. 安装Zookeeper ...

  3. AI人工智能简史

    AI人工智能简史 最近学习AI,顺便整理了一份AI人工智能简史,大家参考: 1951年 第一台神经网络机,称为SNARC: 1956年 达特茅斯学院会议,正式确立了人工智能的研究领域: 1966年 M ...

  4. node服务端

    一,node起服务+数据交互+中间件 什么是node express koa node是js在后端运行时的一个环境 express,koa是基于node的框架,快速构建web应用 前后端交互方式 1. ...

  5. 2015年5月最新win7纯净版系统(32位)补丁最新

    下载地址: http://yunpan.cn/cVN9e679hZ2Pe   访问密码 203a 一.系统安装工具 √ 自由天空最新万能驱动 √ 一键GHOST备份还原系统 √ 硬盘安装系统安装器,增 ...

  6. 2021-04-15:给定一个由字符串组成的数组strs,必须把所有的字符串拼接起来,返回所有可能的拼接结果中,字典序最小的结果。

    2021-04-15:给定一个由字符串组成的数组strs,必须把所有的字符串拼接起来,返回所有可能的拼接结果中,字典序最小的结果. 福大大 答案2021-04-15: "b"和&q ...

  7. 认识 CPU 底层原理(2)——逻辑门

    本文为B站UP主硬件茶谈制作的系列科普<[硬件科普]带你认识CPU>系列的学习笔记,仅作个人学习记录使用,如有侵权,请联系博主删除 上一篇文章我们从最基本的粒子的角度认识了组成CPU的最基 ...

  8. Strings must be encoded before hashing

    Strings must be encoded before hashing 当我们将字符串传递给 hash 算法时,会出现 "TypeError: Strings must be enco ...

  9. 7-2 Broken Pad (20 分)

    1.题目描述: The party began, the greasy uncle was playing cards, the fat otaku was eating, and the littl ...

  10. There is not enough memory to perform the requested operation

    今日在写bug 时 ide 突发脑溢血,崩溃了 一.修改用户目录下的 .vmoptions 找到C:\用户\用户名.WebStorm2018.1\config\webstorm64.exe.vmopt ...