SpringBoot實現利用瀏覽器下載文件

SpringBoot實現利用瀏覽器下載文件

@RestController
@RequestMapping("file")
@Api(tags = "下載文件")
public class downloadFile {
	@GetMapping("/downloadFile")
    public ResponseEntity<FileSystemResource> downloadFile(String path) {
        return export(new File(path));
    }

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }
}

前端傳入路徑,就可以直接下載到瀏覽器了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章