cuốn sách gpt4 ai đã làm

springboot: nhiều cách khác nhau để tải tập tin

In lại Tác giả: Người biết Thời gian cập nhật: 2024-03-12 23:33:39 30 4
mua khóa gpt4 Nike

springboot: nhiều cách khác nhau để tải tập tin

1. Tải xuống bằng luồng đầu ra phản hồi

Lưu ý rằng giá trị trả về của phương thức đầu tiên phải là void

@GetMapping("/t1") public void down1(HttpServletResponse phản hồi) ném Ngoại lệ { reply.reset(); bố trí", "tệp đính kèm; tên tệp=test.png"); thử( BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\desktop\\1.png")); // Luồng đầu ra BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); ​= 0; while ((len = bis.read(buff)) > 0) { bos.write(buff, 0, len); } } }

2. Sử dụng ResponseEntity

@GetMapping("/t2") public ResponseEntity down2() ném Ngoại lệ { inputStreamResource isr = new inputStreamResource(new FileInputStream("E:\\desktop\\1.png")); return ResponseEntity.ok() . contentType(MediaType.APPLICATION_OCTET_STREAM) .header("Bố trí nội dung", "tệp đính kèm; tên tệp=test1.png") .body(isr); } @GetMapping("/t3") public ResponseEntity down3() ném Ngoại lệ { byte[] bytes = Files.readAllBytes(new File("E :\\desktop\\1.png").toPath()); Thanh ByteArrayResource = mới ByteArrayResource(byte); trả về ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header("Content-disposition", "attachment; filename=test2.png") .body(bar);

3. Chú ý

Phần phụ trợ sử dụng một trong ba phương thức đầu tiên, phương thức yêu cầu sử dụng các yêu cầu không GET và giao diện người dùng sử dụng loại Blob để nhận

Trong một số trường hợp, bạn cần POST một số tham số vào phần phụ trợ khi tải xuống. Trong trường hợp này, giao diện người dùng cần hợp tác và đặt loại tiếp nhận thành Blob.

@PostMapping("/t4") public ResponseEntity down4(String fileName, @RequestBody Map data) ném Ngoại lệ { System.out.println(data); byte[] bytes = Files.readAllBytes(new File("E: \\desktop\\1.png").toPath()); Thanh ByteArrayResource = mới ByteArrayResource(byte); trả về ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header("Content-disposition", "attachment; filename=test.png") .body(bar);

Mã giao diện người dùng (ajax gốc được sử dụng ở đây):

    Tiêu đề     Xem sitemap của VNExpress
 
30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress