vue+springboot文件上传下载(前后端分离)
前言
本文提供了文件上传下载案例,前端效果图如下:
一、文件上传
1.前端部分
<!--文件选择框,为了美观设置为隐藏-->
<input
class="file"
type="file"
ref="myfile"
@change="handleBeforeUpload"
style="display: none"
/>
<!--文件上传按钮-->
<div class="upload">
<el-button
@click="clickUpload"
type="primary"
size="mini"
icon="el-icon-upload2"
>上传文件</el-button
>
</div>
2.clickUpload方法(用于触发input标签的点击事件)
clickUpload() {
this.$refs.myfile.click();
},
3.handleBeforeUpload方法(用于上传文件)
axios挂载为:Vue.prototype.$http = axios
async handleBeforeUpload() {
let file = this.$refs.myfile.files[0];
let formData = new FormData();
formData.append("multipartFiles", file);
const { data: res } = await this.$http({
method: "post",
url: "http://localhost:9000/doc/uploadDoc",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
});
if (res.state == 200) {
this.$message.success("上传成功!");
}else{
if(res.state == 303){
this.$message.error("请上传doc或docx文件!");
}else{
this.$message.error("上传失败!");
}
}
//防止选择相同文件不触发文件上传事件
this.$refs.myfile.value = null;
},
4.后端部分
/**
* 上传实施大纲
* @param multipartFiles
* @param courseid
* @return
* @throws SocketException
* @throws IOException
*/
@RequestMapping("/uploadDoc")
public String uploadDoc(MultipartFile[] multipartFiles) throws SocketException, IOException {
File fileDir = new File(rootPath);
if (!fileDir.exists() && !fileDir.isDirectory()) {
fileDir.mkdirs();
}
HashMap<String,Object> result = new HashMap<String,Object>();
try {
if (multipartFiles != null && multipartFiles.length > 0) {
for(int i = 0;i<multipartFiles.length;i++){
try {
if(multipartFiles[i].getOriginalFilename().split("\\.")[1].equals("doc")||multipartFiles[i].getOriginalFilename().split("\\.")[1].equals("docx")){
//文件的保存路径
String storagePath = rootPath+multipartFiles[i].getOriginalFilename().split("\\.")[0]+"."+multipartFiles[i].getOriginalFilename().split("\\.")[1];
logger.info("上传的文件:" + multipartFiles[i].getName() + "," + multipartFiles[i].getContentType() + "," + multipartFiles[i].getOriginalFilename()
+",保存的路径为:" + storagePath);
multipartFiles[i].transferTo(new File(storagePath));
result.put("state",200);
}else{
result.put("state",303);
}
} catch (IOException e) {
e.printStackTrace();
result.put("stete",404);
}
}
}
} catch (Exception e) {
e.printStackTrace();
result.put("state",404);
}
//前端可以通过状态码,判断文件是否上传成功
return JSON.toJSONString(result);
}
rootPath设置为:
private final static String rootPath = "E:/upload/";
二、文件下载
1.前端部分
<!--文件下载-->
<div class="download" v-if="course.dstate!='未上传'">
<el-button size="mini" type="success" icon="el-icon-download" @click="downloadDoc">点击下载</el-button>
</div>
2.downloadDoc方法(实现文件下载)
async downloadDoc() {
let formData = new FormData();
this.$http({
method: "post",
url: "doc/downloadDoc",
data: formData,
responseType: 'blob'
})
.then((res) => {
const blob = res.data;
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e) => {
const a = document.createElement("a");
a.download = this.course.path.split("/")[this.course.path.split("/").length-1];
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
})
.catch((err) => {
console.log(err);
});
},
3.后端部分
/**
* 实施大纲下载
* @param response
* @param id
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping("/downloadDoc")
public String downloadDoc(HttpServletResponse response ) throws UnsupportedEncodingException {
//要下载的文件路径
File file = new File("E:/upload.txt");
//下载后的文件名
String fileName = "下载文件.txt"
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Content-Length",""+file.length());
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
logger.info("文件下载完成!!");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}