今天看到同事的代碼宇整,發(fā)現(xiàn)返回文件還是用的古老的方式
d82fbb390863cb87a81f98c45e78eb3.png
更優(yōu)雅的方式是使用spring的resource接口
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
...
@GetMapping("/image/{path}")
public ResponseEntity<Resource> download(@PathVariable String path) {
String contentDisposition = ContentDisposition
.builder("attachment")
.filename(path)
.build().toString();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.contentType(MediaType.IMAGE_JPEG)
.body(new FileSystemResource(path));
}
轉(zhuǎn)載必須附上原文鏈接