SpringBoot实现数据下资源的永久地址
目的:实现数据下资源的永久地址,无论这条数据下文件资源被替换成何种文件,但是预览地址始终不变
/**
* 预览或下载文件
* @param id 资源id
* @return 文件
*/
@GetMapping("/preview/{id}")
public ResponseEntity<org.springframework.core.io.Resource> preview(@PathVariable("id") Long id) {
LayoutResource layoutResource = layoutResourceService.getById(id);
if(ObjectUtil.isEmpty(layoutResource)){
throw new ServiceException("资源不存在");
}
SysOssVo sysOssVo = sysOssService.getById(layoutResource.getOssId());
String contentType = getContentType(sysOssVo.getUrl());
InputStream inputStream = sysOssService.getObjectContent(layoutResource.getOssId());
boolean hasImage = isImage(sysOssVo.getFileName());
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, hasImage ? "inline" : "attachment; filename=\""
+ java.net.URLEncoder.encode(sysOssVo.getOriginalName(),StandardCharsets.UTF_8) + "\"")
.contentType(MediaType.parseMediaType(contentType))
.body(new InputStreamResource(inputStream));
}
/**
* 获取文件类型
* @param urlString URL地址
* @return 文件类型
*/
private String getContentType(String urlString){
String contentType = null;
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
connection.connect();
contentType = connection.getContentType();
} catch (Exception e) {
e.printStackTrace();
}
return contentType;
}