浏览代码

文件下载和文件预览功能

DESKTOP-2K9OVK9\siwei 6 月之前
父节点
当前提交
dfc5472f21

+ 108 - 0
onemap-modules/onemap-file/src/main/java/com/onemap/file/controller/SysFileController.java

@@ -5,16 +5,35 @@ import com.onemap.common.core.web.domain.RequestResult;
 import com.onemap.file.domain.TUploadGeomDTO;
 import com.onemap.file.service.ISpaceFileRecordService;
 import com.onemap.file.service.SaveFileService;
+import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.AntPathMatcher;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 import com.onemap.common.core.domain.R;
 import com.onemap.common.core.utils.file.FileUtils;
 import com.onemap.file.service.ISysFileService;
 import com.onemap.system.api.domain.SysFile;
+import org.springframework.web.servlet.HandlerMapping;
+import org.springframework.web.util.UriUtils;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -33,6 +52,7 @@ public class SysFileController {
     private ISpaceFileRecordService spaceFileRecordService;
     @Autowired
     private SaveFileService saveFileService;
+    private AntPathMatcher antPathMatcher = new AntPathMatcher();
 
     /**
      * 文件上传
@@ -267,5 +287,93 @@ public class SysFileController {
         return RequestResult.success("执行成功!", spaceFileRecordService.selectTUploadGeomDetailsById(id));
     }
 
+    /**
+     * 文件预览
+     *
+     * @param request
+     * @param response
+     * @return
+     */
+    @GetMapping("/upload/inline/**")
+    public ResponseEntity<Resource> uploadInline(HttpServletRequest request, HttpServletResponse response) {
+        try {
+            String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
+            String bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
+            // 提取与模式相匹配的部分(不包括通配符)
+            String extractedPath = antPathMatcher.extractPathWithinPattern(bestMatchingPattern, path);
+            String uploadFile = spaceFileRecordService.uploadAbsolutePath(extractedPath);
+            // 构建文件的完整路径
+            Path filePath = Paths.get(uploadFile);
+            Resource resource = new FileSystemResource(filePath.toFile());
+            // 如果资源不存在,返回404
+            if (!resource.exists()) {
+                return ResponseEntity.notFound().build();
+            }
+            // 获取文件MIME类型
+            String contentType = Files.probeContentType(filePath);
+            if (contentType == null) {
+                // 如果无法确定MIME类型,则使用默认值
+                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
+            }
+            // 设置HTTP头部信息
+            HttpHeaders headers = new HttpHeaders();
+            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + URLEncoder.encode(resource.getFilename(), "UTF-8") + "\"");
+//            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");
+            headers.setContentType(MediaType.parseMediaType(contentType));
+
+            // 返回文件资源
+            return ResponseEntity.ok().headers(headers).contentLength(Files.size(filePath))  // 可选:设置内容长度
+                    .body(resource);
+        } catch (IOException e) {
+            // 处理IO异常,例如文件不存在或无法读取
+//            e.printStackTrace();
+            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
+        }
+    }
+
+    /**
+     * 文件下载
+     *
+     * @param request
+     * @param response
+     * @return
+     */
+    @GetMapping("/upload/attachment/**")
+    public ResponseEntity<Resource> uploadInline(HttpServletRequest request, HttpServletResponse response) {
+        try {
+            String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
+            String bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
+            // 提取与模式相匹配的部分(不包括通配符)
+            String extractedPath = antPathMatcher.extractPathWithinPattern(bestMatchingPattern, path);
+            String uploadFile = spaceFileRecordService.uploadAbsolutePath(extractedPath);
+            // 构建文件的完整路径
+            Path filePath = Paths.get(uploadFile);
+            Resource resource = new FileSystemResource(filePath.toFile());
+            // 如果资源不存在,返回404
+            if (!resource.exists()) {
+                return ResponseEntity.notFound().build();
+            }
+            // 获取文件MIME类型
+            String contentType = Files.probeContentType(filePath);
+            if (contentType == null) {
+                // 如果无法确定MIME类型,则使用默认值
+                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
+            }
+            // 设置HTTP头部信息
+            HttpHeaders headers = new HttpHeaders();
+//            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + URLEncoder.encode(resource.getFilename(), "UTF-8") + "\"");
+            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(resource.getFilename() + "\"");
+            headers.setContentType(MediaType.parseMediaType(contentType));
+
+            // 返回文件资源
+            return ResponseEntity.ok().headers(headers).contentLength(Files.size(filePath))  // 可选:设置内容长度
+                    .body(resource);
+        } catch (IOException e) {
+            // 处理IO异常,例如文件不存在或无法读取
+//            e.printStackTrace();
+            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
+        }
+    }
+
 
 }

+ 16 - 0
onemap-modules/onemap-file/src/main/java/com/onemap/file/service/ISpaceFileRecordService.java

@@ -6,6 +6,11 @@ import com.onemap.file.domain.TUploadGeomDTO;
 import com.onemap.file.domain.TUploadGeomDetailsDTO;
 import org.springframework.web.multipart.MultipartFile;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
 public interface ISpaceFileRecordService {
 
     /**
@@ -79,4 +84,15 @@ public interface ISpaceFileRecordService {
      */
     public void handleUploadGeomFollowUp(String id, Integer followup);
 
+
+    /**
+     * 上传文件绝对地址
+     * <p>
+     * <br/>
+     * 如果地址有异常,返回为空
+     *
+     * @param file
+     */
+    String uploadAbsolutePath(String file);
+
 }

+ 20 - 3
onemap-modules/onemap-file/src/main/java/com/onemap/file/service/impl/SpaceFileRecordServiceImpl.java

@@ -23,15 +23,24 @@ import com.onemap.system.api.domain.RawTableVo;
 import com.onemap.file.domain.res.ApiTTable;
 import com.onemap.file.domain.res.ApiTTableFiled;
 import com.onemap.file.domain.res.TableDataVo;
+import org.apache.commons.io.IOUtils;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.util.UriUtils;
 
 import javax.annotation.Resource;
 import javax.annotation.processing.FilerException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
@@ -53,6 +62,8 @@ public class SpaceFileRecordServiceImpl implements ISpaceFileRecordService {
     private SpatialService spatialService;
     @Value("${businessType.shp}")
     private String shpLocalFilePath;
+    @Value("${file.path}")
+    private String uploadFilePath;
     @Resource
     private SpaceFileRecordMapper spaceFileRecordMapper;
     @Resource
@@ -256,7 +267,7 @@ public class SpaceFileRecordServiceImpl implements ISpaceFileRecordService {
         // 获取当前时间的时间戳
         long timeMillis = System.currentTimeMillis();
         //生成SHP解压文件路径
-        String unzipPath = shpLocalFilePath + "/temp" + "/" + timeMillis;
+        String unzipPath = uploadFilePath + "/temp" + "/" + timeMillis;
         //解压文件
         uploadDestMultipartFile(file, unzipPath);
 
@@ -278,9 +289,9 @@ public class SpaceFileRecordServiceImpl implements ISpaceFileRecordService {
         dto.setFromroute(fromRoute);
         dto.setName(fileName);
         dto.setFiletype(type);
-        dto.setUnzippath(unzipPath.replace("\\", "/"));
+        dto.setUnzippath(unzipPath.replace("\\", "/").substring(uploadFilePath.length()));
         if (newShpPath != null) {
-            dto.setShppath(newShpPath.replace("\\", "/"));
+            dto.setShppath(newShpPath.replace("\\", "/").substring(uploadFilePath.length()));
         }
 
         List<Map<String, Object>> shpFeaturesList = shpFileSaveService.readShapeFile(newShpPath);
@@ -365,4 +376,10 @@ public class SpaceFileRecordServiceImpl implements ISpaceFileRecordService {
         System.out.println("handleUploadGeomFollowUp!!!!!!!");
     }
 
+
+    @Override
+    public String uploadAbsolutePath(String file) {
+        String unzipPath = uploadFilePath + file;
+        return unzipPath;
+    }
 }