Parcourir la source

GetObjectService 添加 writeNotFound 方法, 文件在磁盘中不存在时调用

reghao il y a 6 mois
Parent
commit
ce47eac2df

+ 18 - 0
oss-store/src/main/java/cn/reghao/oss/store/service/GetObjectService.java

@@ -75,6 +75,13 @@ public class GetObjectService {
     }
 
     public void getObject(ObjectMeta objectMeta) throws IOException {
+        String absolutePath = objectMeta.getAbsolutePath();
+        File file = new File(absolutePath);
+        if (!file.exists()) {
+            writeNotFound();
+            return;
+        }
+
         String host = ServletUtil.getRequest().getHeader("host");
         long len = objectMeta.getSize();
         String range = ServletUtil.getRequest().getHeader("range");
@@ -184,6 +191,17 @@ public class GetObjectService {
         writeResponse(outputStream, objectMeta.getAbsolutePath(), 0, objectMeta.getSize());
     }
 
+    private void writeNotFound() throws IOException {
+        HttpServletResponse response = ServletUtil.getResponse();
+        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+        /*response.setContentType(objectMeta.getContentType());
+        response.setHeader("Content-Length", ""+objectMeta.getSize());*/
+
+        OutputStream outputStream = response.getOutputStream();
+        outputStream.flush();
+        outputStream.close();
+    }
+
     private void writeResponse(OutputStream outputStream, String absolutePath, long start, long end) throws IOException {
         RandomAccessFile raf = new RandomAccessFile(absolutePath, "r");
         raf.seek(start);