8.文件上传
一、Spring Boot 默认使用 springMVC 包装好的解析器进行上传
二、添加代码
模板中使用
<form method="POST" enctype="multipart/form-data" action="/file/upload"> 文件:
<input type="file" name="testFile" />
<input type="submit" value="上传" />
</form>
@Controller
@RequestMapping(value = "/file")
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@RequestMapping(value = "upload")
@ResponseBody
public String upload(@RequestParam("testFile") MultipartFile file) {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("上传的后缀名为:" + suffixName);
// 文件上传路径
String filePath = "/tmp/test/";
// 解决中文问题,liunx 下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
三、配置
spring.http.multipart.enabled=true #默认支持文件上传.
spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.
spring.http.multipart.location= # 上传文件的临时目录
spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
spring.http.multipart.max-request-size=10Mb # 最大支持请求大小
附录:
rest 上传,下载示例
@RestController @RequestMapping("/file") public class FileController { @PostMapping("/upload") public FileInfo update(MultipartFile file) throws Exception { System.out.println(file.getContentType()); System.out.println(file.getName()); System.out.println(file.getOriginalFilename()); System.out.println(file.getSize()); String path = "/tmp"; String extention = StringUtils.substringAfterLast(file.getOriginalFilename(), "."); File localfile = new File(path, new Date().getTime()+"."+extention); file.transferTo(localfile); return new FileInfo(localfile.getAbsolutePath()); } @GetMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) throws Exception { String filePath = "/tmp/1111.txt"; try(InputStream inputStream = new FileInputStream(filePath); OutputStream outputStream = response.getOutputStream();){ response.setContentType("application/x-download"); response.addHeader("Content-Disposition", "attachment;filename=test.txt"); IOUtils.copy(inputStream, outputStream); outputStream.flush(); } } }
注意上面下载的时候try使用了新特性,在try括号中声明了资源,他会在执行完成后自动释放掉,否则需要自己写finaly释放资源。
FileInfo.java
public class FileInfo { public FileInfo(String path) { this.path = path; } private String path; .....省略get set方法 }
资料
Last updated