文件上传、下载

文件上传

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/** 
* 上传文件到服务器--创建一个工具类,直接调用该方法即可
* @param mulFile:文件流
* @param uploadPath:文件上传后存储的路径
* @return
*/
public static File uploadFile(MultipartFile mulFile, String uploadPath) {

String fileName = mulFile.getOriginalFilename();// 获取文件名(包括后缀名)
String suffixName = fileName.substring(fileName.lastIndexOf("."));// 获取文件的后缀名
String infrontName = fileName.substring(0,fileName.lastIndexOf("."));//获取文件的文件名

String timestamp = new Timestamp(System.currentTimeMillis()).getTime()+"";//当前时间戳
String filePath = uploadPath + infrontName + "-" + timestamp + suffixName;// 给名字添加时间戳

/**
* 文件存储
*/
File target = new File(filePath);// 创建一个新文件
if (!target.getParentFile().exists()) {// 检测是否存在目录
target.getParentFile().mkdirs();// 新建文件夹
}
try {
mulFile.transferTo(target);// 把file文件写入dest
} catch (IOException e) {
e.printStackTrace();
}
return target;
}

Controller

1
2
3
4
5
6
7
8
@RequestMapping(value = "reload", method = RequestMethod.POST)
public String uploadFile(@RequestParam(value = "mulFile", required = false) MultipartFile uploadfile,
@RequestParam(value = "id", required = true, defaultValue = "") String id) {

String uploadPath = "d:/file";
File result = uploadFile(uploadfile,uploadPath);
return "";
}

请求

1
2
3
4
{
"id":11,
"mulFile":"#@#!%@#*!%$"//文件流
}

文件下载

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 提供文件下载
* @return 返回结果集
*/
@RequestMapping(value = "/io", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public ResponseEntity<InputStreamResource> download(@RequestParam(value = "id") Integer id) throws Exception {


val filePath = "D:/file/haha1534299140658.csv";

val file = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");

try {
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
log.info("==== 文件下载出现异常:IOException::位置:HFileController.download/GET ===");
}
return null;
}

创建 MultipartFile 对象 供后端测试

核心代码

创建

1
2
3
4
5
6
7
8
String path = "d:/";
File file = new File(path + "haha.csv");
MultipartFile mulFile = new MockMultipartFile(
"haha4.csv", //文件名
"haha2.csv", //originalName 相当于上传文件在客户机上的文件名
ContentType.APPLICATION_OCTET_STREAM.toString(), //文件类型
new FileInputStream(file) //文件流
);