@@ -306,34 +306,43 @@ public Result<Resource> detail(@PathVariable Integer id) {
306306 })
307307 @ SystemControllerLog (description = "获取资源" )
308308 @ GetMapping ("/resource/download/{name}" )
309- public void getResource (@ PathVariable String name ,
310- HttpServletResponse response ) throws Exception {
311- if (name == null ) {
312- throw new ServiceException (ExceptionEnum .CM009 .getResultCode (),ExceptionEnum .CM009 .getResultMsg ());
309+ public void getResource (@ PathVariable String name , HttpServletResponse response ) throws Exception {
310+ // 参数校验
311+ if (name == null || name . trim (). isEmpty () ) {
312+ throw new ServiceException (ExceptionEnum .CM009 .getResultCode (), ExceptionEnum .CM009 .getResultMsg ());
313313 }
314+
314315 Resource resource = resourceService .queryResourceByName (name );
315- if (resource == null ) {
316- throw new ServiceException (ExceptionEnum .CM009 .getResultCode (),ExceptionEnum .CM009 .getResultMsg ());
316+ if (resource == null ) {
317+ throw new ServiceException (ExceptionEnum .CM009 .getResultCode (), ExceptionEnum .CM009 .getResultMsg ());
317318 }
318-
319+ // 获取图片数据
319320 String base64Data = Utils .isResource (name ) ? resource .getResourceData () : resource .getThumbnailData ();
321+ if (base64Data == null || base64Data .trim ().isEmpty ()) {
322+ throw new ServiceException (ExceptionEnum .CM009 .getResultCode (), "资源数据为空" );
323+ }
324+
320325 String cleanBase64 = ImageThumbnailGenerator .extractCleanBase64 (base64Data );
321326 byte [] imageBytes = Base64 .getDecoder ().decode (cleanBase64 );
322-
327+ // 设置响应头
323328 String detectedType = ImageThumbnailGenerator .extractContentType (base64Data );
329+ String encodedFileName = URLEncoder .encode (name , StandardCharsets .UTF_8 ).replace ("+" , "%20" );
324330
325- // URL编码文件名
326- String encodedFileName = URLEncoder .encode (name , StandardCharsets .UTF_8 )
327- .replace ("+" , "%20" );
331+ // 设置必要的HTTP头
328332 response .setContentType (detectedType );
333+ response .setContentLength (imageBytes .length );
334+ response .setHeader ("Cache-Control" , "public, max-age=3600" ); // 添加缓存控制
335+ response .setHeader ("Accept-Ranges" , "bytes" ); // 支持断点续传
329336
330- // 只使用 filename* 格式,避免中文字符直接出现在header中
331- response .setHeader ("Content-Disposition" , "inline; filename*=UTF-8''" + encodedFileName );
332- if (Utils .isDownload (name )){
333- response .setHeader ("Content-Disposition" , "attachment ; filename*=UTF-8''" + encodedFileName );
334- }
337+ // 设置Content-Disposition
338+ String contentDisposition = Utils .isDownload (name )
339+ ? "attachment; filename*=UTF-8''" + encodedFileName
340+ : "inline; filename*=UTF-8''" + encodedFileName ;
341+ response .setHeader ("Content-Disposition" , contentDisposition );
342+ // 写入响应体
335343 try (OutputStream out = response .getOutputStream ()) {
336344 out .write (imageBytes );
345+ out .flush ();
337346 }
338347 }
339348}
0 commit comments