Springboot与Vue整合,实现文件上传与下载功能
yml相关配置:
# 自定义属性(文件上传/下载路径,可配置参数)
download:
filePath: D:\\MyComputer\\小辰哥哥\\
1.文件下载功能
后端控制器代码:
package com.kd.opt.controller;
import com.kd.opt.util.OptDataUtil;
import com.kd.opt.util.ReturnDataUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
/**
* 关于文件上传与下载
*
* @author 小辰哥哥
*/
@RestController
@CrossOrigin
@RequestMapping("/fileOperationController")
public class FileOperationController {
// 文件上传/下载路径(可配置参数)
@Value("${download.filePath}")
private String filePath;
/**
* 文件下载
*
* @param fileName
* @return
* @author 小辰哥哥
*/
@PostMapping("/download")
public byte[] downloadFile(@RequestParam("fileName") String fileName) {
// 关联文件
File file = new File(filePath + fileName);
byte[] fileBytes = null;
FileInputStream fileInputStream = null;
ByteArrayOutputStream bos = null;
try {
fileInputStream = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while ((len = fileInputStream.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
fileBytes = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileBytes;
}
}
前端Vue代码:
<el-button type="warning" round @click="download">下载按钮</el-button>
// download方法
download() {
var params = new URLSearchParams();
params.append("fileName", "小辰哥哥.docx");
this.$axios({
// 根据自己项目情况如实填写
url: "/fileOperationController/download",
method: "post",
data: params,
responseType: 'blob',
}).then(data => {
// 获取数据(重点如何处理数据)
var response = data.data;
let url = window.URL.createObjectURL(new Blob([response]));
let a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// 设置新文件名称(注意文件后缀名)
a.setAttribute('download', '小辰哥哥我爱你.docx');
document.body.appendChild(a);
// 点击下载
a.click();
// 下载完成移除元素
document.body.removeChild(a);
// 释放掉blob对象
window.URL.revokeObjectURL(url);
}).catch(error => {
this.$message({message: '网络连接异常', type: 'error'});
})
}
文件所在位置:
开始测试:
2.文件上传功能
后端控制器代码:
package com.kd.opt.controller;
import com.kd.opt.util.OptDataUtil;
import com.kd.opt.util.ReturnDataUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
/**
* 关于文件上传与下载
*
* @author 小辰哥哥
*/
@RestController
@CrossOrigin
@RequestMapping("/fileOperationController")
public class FileOperationController {
// 文件上传/下载路径(可配置参数)
@Value("${download.filePath}")
private String filePath;
/**
* 文件上传
*
* @param fileName
* @return
* @author 小辰哥哥
*/
@PostMapping("/upload")
public OptDataUtil uploadFile(@RequestParam("file") MultipartFile fileName) {
try {
// 关联文件
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream writer = new FileOutputStream(new File(file, fileName.getOriginalFilename()));
writer.write(fileName.getBytes());
writer.flush();
writer.close();
return ReturnDataUtil.getSuccess("200");
} catch (Exception e) {
return ReturnDataUtil.getFailCodeMessage("500", "文件上传失败");
}
}
}
前端Vue代码(Element UI框架复用):
<el-upload
class="upload-demo"
:action="uploadUrl"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
data() {
return {
// 请求后端服务器的接口地址
uploadUrl: this.$axios.defaults.baseURL+"/fileOperationController/upload",
// 框架中的案例(可以忽略)
fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
}
},
methods: {
// 框架中的案例(可以忽略)
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
}
}
开始测试:
总结
每天一个提升小技巧!!!