文件预览与下载

  @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        Resource resource = storageService.loadFileAsResource(fileName);
        String contentType;
        ResponseEntity<Resource> body = null;
        try{
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
            if (contentType == null){
                contentType = "application/octet-stream";
            }
             body = ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(Objects.requireNonNull(resource.getFilename()), "UTF-8"))
                    .body(resource);
        }catch (IOException ex){
            logger.info("Could not determine file type");
            ex.printStackTrace();
        }
        return body;
    }
    /**
     * ResponseEntity图片预览
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/preview/{fileName:.+}")
    public ResponseEntity<Resource> responseEntityView(@PathVariable String fileName){
        WsslFileS storage = fileService.getEntityByKey(fileName);
        if (fileName == null) {
            return ResponseEntity.notFound().build();
        }
        if (fileName.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        String type = storage.getFileType();
        MediaType mediaType = MediaType.parseMediaType(type);
        Resource file = storageService.loadFileAsResource(fileName);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }
posted @ 2022-10-12 09:19  肖恩雷  阅读(216)  评论(0编辑  收藏  举报