项目结构

  • 后端

  • 前端

效果演示

  • 上传文件

  • 下载文件

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. 在CentOS上安装与卸载Docker Engine

    本文参考Docker官网提供的 安装手册编写 测试使用的操作系统版本为CentOS 7.9 安装Docker Engine 要在 CentOS 上开始使用 Docker 引擎,请确保 满足先决条件,然 ...

  2. 2023成都.NET线下技术沙龙圆满结束

    2023年4月15日周六,由MASA技术团队和成都.NET俱乐部共同主办的2023年成都.NET线下技术沙龙活动在成都市世纪城新会展中心知域空间举行,共计报名人数90多人,实际到场60多人,13:30 ...

  3. JS中的Map、Set、WeakMap和WeakSet

    在JavaScript中,Map.Set.WeakMap和WeakSet是四个不同的数据结构,它们都有不同的特点和用途: 1. Map :Map是一种键值对的集合,其中的键和值可以是任意类型的.与对象 ...

  4. [OpenCV-Python] 24 模板匹配

    文章目录 OpenCV-Python:IV OpenCV中的图像处理 24 模板匹配 24.1 OpenCV 中的模板匹配 24.2 多对象的模板匹配 OpenCV-Python:IV OpenCV中 ...

  5. 2023-03-23:音视频解混合(demuxer)为PCM和YUV420P,用go语言编写。

    2023-03-23:音视频解混合(demuxer)为PCM和YUV420P,用go语言编写. 答案2023-03-23: 大体步骤如下: 1.打开媒体文件,并获取音频和视频流. 2.对于每个流,找到 ...

  6. 2023-03-12:mp3音频解码为pcm,代码用go语言编写,调用moonfdd/ffmpeg-go库。

    2023-03-12:mp3音频解码为pcm,代码用go语言编写,调用moonfdd/ffmpeg-go库. 答案2023-03-12: 用github/moonfdd/ffmpeg-go库. 命令如 ...

  7. 2022-07-14:以下go语言代码输出什么?A:1;B:3;C:4;D:编译错误。 package main import ( “fmt“ ) func main() { a

    2022-07-14:以下go语言代码输出什么?A:1:B:3:C:4:D:编译错误. package main import ( "fmt" ) func main() { a ...

  8. 2020-12-15:mysql的回滚机制是怎么实现的?

    福哥答案2020-12-15:[答案来自此链接:](https://www.cnblogs.com/ld-swust/p/5607983.html)在 MySQL 中,恢复机制是通过回滚日志(undo ...

  9. 2021-12-28:给定一个二维数组matrix,matrix[i][j] = k代表: 从(i,j)位置可以随意往右跳<=k步,或者从(i,j)位置可以随意往下跳<=k步, 如果matrix[i]

    2021-12-28:给定一个二维数组matrix,matrix[i][j] = k代表: 从(i,j)位置可以随意往右跳<=k步,或者从(i,j)位置可以随意往下跳<=k步, 如果mat ...

  10. 2021-06-12:已知一棵搜索二叉树上没有重复值的节点,现在有一个数组arr,是这棵搜索二叉树先序遍历的结果。请根据arr生成整棵树并返回头节点。

    2021-06-12:已知一棵搜索二叉树上没有重复值的节点,现在有一个数组arr,是这棵搜索二叉树先序遍历的结果.请根据arr生成整棵树并返回头节点. 福大大 答案2021-06-12: 先序遍历+中 ...