文件上传
1.在application文件中设置相关参数
#上传单个文件的最大值
spring.http.multipart.max-file-size=10MB
#上传多个文件的最大值
spring.http.multipart.max-request-size=50MB
#文件上传路径
spring.http.multipart.location=D:\\Temp
2.定义html文件
也可以定义模板文件,注意表单的类型使用“post”方法,并且媒体类型是二进制类型“multipart/form-dat”,并且定义访问请求为"fileUpload"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h1>Hello Boy!文件上传测试</h1>
<form method="post" enctype="multipart/form-data" action="/fileUpload">
<input type="file" name="fileUpload">
<input type="submit" value="upload">
</form>
</body>
</html>
3. 编写Controller类
Controller类将文件上传请求映射到处理文件上传的方法。
这里可通过@ConfigurationProperties?将properties的内容注入到Controller的字段,可以在程序中使用,例如显示上传的最大限制等。
并且使用MultipartFile对象获取文件上传对象。
这里使用MultipartFile对象的transferTo()方法来实现文件上传,也可以自己编写文件传输的代码,如使用FIS/FOS,RandomAccess等。
@Controller
@ConfigurationProperties(prefix = "spring.http.multipart")
public class FileUploadController {
private String location;
private String maxFileSize;
private String maxRequestSize;
@RequestMapping(path = "/fileUpload")
@ResponseBody
public String fileUpload(@RequestParam(value = "fileUpload") MultipartFile file) {
if (file == null) {
return "未指定文件";
}
String filePath = location + File.separator + file.getOriginalFilename();
File dest = new File(filePath);
try {
file.transferTo(dest);
return "文件上传成功";
} catch (IOException e) {
return "文件上传失败";
}
}
…… get/set方法
}
注意:前端页面form表单file组件的name要和后端方法的参数保持一致,这里前端form的name为“fileUpload”,后端为“file”,需要使用@RequestParam标识,否则会导致MultipartFile对象注入为null。
4.测试
文件下载
这里为下载固定的文件
Controller如下
注意,文件的下载是借助response的输出流实现的,这里使用了BIS加速文件载入内存的速度。
这里设置响应头中HTTP字段“ContentTyp:application/octet-stream”,这个字段的意思是二进制流,但不知道文件的类型,可以视为任意文件的下载。
@Controller
public class FileDownloadController {
@RequestMapping(path = "filedownload")
@ResponseBody
public void fileDownload(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
String fileName = "D:\\Temp\\5610.png";
File file = new File(fileName);
if (!file.exists()) {
System.out.println("文件不存在");
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ServletOutputStream sos = httpServletResponse.getOutputStream();) {
//二进制文件流形式
httpServletResponse.setContentType("application/octet-stream");
//设置文件的下载方式
httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
byte[] buffer = new byte[1 << 10];
int readLen = 0;
while ((readLen = bis.read(buffer, 0, buffer.length)) > 0) {
sos.write(buffer, 0, readLen);
}
System.out.println("下载成功");
} catch (Exception e) {
System.out.println("下载失败");
}
}
}
测试