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));
}
}
前端传入路径,就可以直接下载到浏览器了。