2022-06-17 4 分钟 0.5 k0次访问
文件上传和下载
页面文件
1 2 3 4 5
| <form action="/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form>
|
controller
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 31 32 33 34 35 36 37 38
| @RestController @RequestMapping("/file") public class FileController {
@PostMapping("/upload") public String upload(MultipartFile file) throws Exception { String filename = file.getOriginalFilename(); FileOutputStream outputStream = new FileOutputStream(new File("e:/upload/",filename)); outputStream.write(file.getBytes()); outputStream.flush(); outputStream.close(); return "上传成功"; } @GetMapping("/download") public void download(String filename, HttpServletResponse response) throws Exception{ FileInputStream inputStream = new FileInputStream(new File("e:/upload/", 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(); }
|
使用transferTo方法
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 31 32 33 34 35 36 37 38
| @RestController @RequestMapping("/file") public class FileController {
@PostMapping("/upload") public String upload(MultipartFile file) throws Exception { String originalFilename = file.getOriginalFilename(); Path path = Paths.get("e:/upload/"); if(!Files.exists(path)){ Files.createDirectory(path); } String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1, originalFilename.length()); String newFileName = UUID.randomUUID().toString()+"."+ext; file.transferTo(new File(String.valueOf(path),newFileName)); return "上传成功"; } @GetMapping("/download") public void download(String filename, HttpServletResponse response) throws Exception{ Path path = Paths.get("e:/upload/" + filename); response.setHeader("content-disposition", "attachment; filename=" + filename); WritableByteChannel writableByteChannel = Channels.newChannel(response.getOutputStream()); FileChannel fileChannel = new FileInputStream(path.toFile()).getChannel(); fileChannel.transferTo(0, fileChannel.size(), writableByteChannel); fileChannel.close(); writableByteChannel.close(); } }
|