项目结构
-
后端
image.png -
前端
image.png
效果演示
-
上传文件
image.png -
下载文件
image.png
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();
}).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";
}
网友评论