前面搜索了几个关于springboot+vue+elementui上传下载的文章,感觉写的都不尽如人意。要么是功能不完善,不好用。再者就是源码提供的实在差劲,都不完整。一气之下,自己搞了一个实用的完整版DEMO,有需要的朋友拿走稍加改动就能使用。
项目源码源码已经整理好了,如何运行直接看根路径下的README.md。
https://gitee.com/indexman/springbootdemo
效果展示
Vue文件上传下载删除DEMO
点击上传
后端代码
package com.java.bootdemo.vue_upload_demo.controller;
import com.java.bootdemo.common.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/file")
public class FileController {
// 设置固定的日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 将 yml 中的自定义配置注入到这里
@Value("${app.uploadPath}")
private String uploadPath;
// 日志打印
private Logger log = LoggerFactory.getLogger("FileController");
// 文件上传 (可以多文件上传)
@PostMapping("/upload")
public Result fileUploads(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
// 获取上传的文件名称
String fileName = file.getOriginalFilename();
// 得到文件保存的位置以及新文件名
File dest = new File(uploadPath + fileName);
// 判断Path是否存在,不存在就创建
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
// 上传的文件被保存了
file.transferTo(dest);
// 打印日志
log.info("上传成功,当前上传的文件保存在 {}",uploadPath + fileName);
// 自定义返回的统一的 JSON 格式的数据,可以直接返回这个字符串也是可以的。
Map map = new HashMap<>();
map.put("filename",fileName);
return new Result<>().ok(map);
} catch (IOException e) {
log.error(e.toString());
}
// 待完成 —— 文件类型校验工作
return new Result().error("上传失败");
}
@PostMapping("/remove")
public Result remove(@RequestParam String filename){
File dest = new File(uploadPath + filename);
if(dest.exists()){
// 上传的文件被保存了
dest.delete();
// 打印日志
log.info("{}删除成功",filename);
return new Result<>().ok("删除成功");
}
// 待完成 —— 文件类型校验工作
return new Result().error("删除失败");
}
@GetMapping("/download")
public void download(@RequestParam String filename, HttpServletResponse response) throws UnsupportedEncodingException {
File dest = new File(uploadPath + filename);
if(dest.exists()){
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) dest.length());
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode( filename , "UTF-8"));
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(dest));) {
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
log.error("{}",e);
}
}
}
}



