简单文件上传与下载
上传
配置文件
1 2 3 4 5
| spring: servlet: multipart: max-file-size: 300MB max-request-size: 300MB
|
前端代码
1 2 3 4 5 6 7 8 9 10 11 12
| <form action="/admin/upload" method="post" enctype="multipart/form-data" class="ui form"> <div class="required field"> <div class="ui left labeled input"> <input type="file" name="file"> </div> </div> <div class="ui right aligned container"> <button class="ui teal submit button">提交</button> <button type="button" class="ui button" onclick="window.history.go(-1)">返回</button> </div> </form>
|
后端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Controller public class UploadController {
@Value("static/files") private String fileLocation;
@PostMapping("/admin/upload") public String upload(MultipartFile file, Model model) throws IOException { System.out.println("进入upload"); String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation; File newFile = new File(realPath); if (!newFile.exists()){ newFile.mkdirs(); } Date date = new Date(); String fileName = date.getTime() +"@" + file.getOriginalFilename(); file.transferTo(new File(newFile, fileName)); return "admin/upload"; } }
|
示例
下载
后端
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
| @Controller public class UploadController {
@Value("static/files") private String fileLocation;
@GetMapping("/admin/download") public void download(String fileName, HttpServletResponse response) throws IOException { System.out.println("download"); String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation; FileInputStream inputStream = new FileInputStream(new File(realPath, fileName)); response.setHeader("content-disposition", "attachment; fileName=" + fileName); ServletOutputStream outputStream = response.getOutputStream(); int len = 0; byte[] data = new byte[1024]; while ((len = inputStream.read(data)) != -1) { outputStream.write(data, 0, len); } outputStream.close(); inputStream.close(); } }
|
请求方式
http://localhost:8080/admin/download?fileName=1631839958785@13.jpg