java下载静态资源文件

直接返回资源文件下载

  @GetMapping("/template")
  public ResponseEntity<org.springframework.core.io.Resource> getTemplate(HttpServletRequest request) {
      ResponseEntity<org.springframework.core.io.Resource> body = null;
      try {
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      org.springframework.core.io.Resource resources = resolver.getResources("/static/template.doc")[0];

      String contentType;
      contentType =
            request.getServletContext().getMimeType(resources.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(resources.getFilename()), "UTF-8"))
                .body(resources);

      } catch (IOException ex) {
          log.info("Could not determine file type");
          ex.printStackTrace();
      }
        return body;
    }

资源文件上传到本地服务器后,返回下载路径

 @GetMapping("/template")
    public Object getTemplate(HttpServletRequest request) {
        ResponseEntity<org.springframework.core.io.Resource> body = null;
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            org.springframework.core.io.Resource resource = resolver.getResources("/static/template.doc")[0];
            storageService.storeFile(resource.getInputStream(),resource.getFile().length(),"application/msword",resource.getFilename());
            String fileDownloadUrl = ServletUriComponentsBuilder
                    .fromCurrentContextPath()
                    .path("/file/download/")
                    .path(resource.getFilename()).toUriString();
            String filePreviewUrl = ServletUriComponentsBuilder
                    .fromCurrentContextPath()
                    .path("/file/preview/")
                    .path(resource.getFilename()).toUriString();

            WsslFileS storage = new WsslFileS();
            storage.setFileDownloadUrl(fileDownloadUrl);
            storage.setFilePreviewUrl(filePreviewUrl);
            storage.setFileName(resource.getFilename());
            storage.setFileSize((double)resource.getFile().length());
            storage.setFileType("application/msword");
            storage.setFileCode(resource.getFilename());
            storage.setDeleted(false);
            fileService.save(storage);

            return ResponseUtil.ok(storage);
        } catch (CustomException e) {
            log.error(e.getMessage());
            return ResponseUtil.fail(e.getMessage());
        } catch (Exception e) {
            log.error("系统异常", e);
            return ResponseUtil.serious();
        }

StorageService服务

public interface StorageService {
    String storeFile(InputStream inputStream, long contentLength, String contentType, String fileName);

    Resource loadFileAsResource(String fileName);
}

StorageService服务实现类

@Service
public class StorageServiceImpl implements StorageService {

    private final Path fileStorageLocation;


    @Autowired
    public StorageServiceImpl(FileStorageProperties fileStorageProperties) {
        this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception ex) {
            throw new FileStorageException("Could not create directory where the uploaded files will be stored");
        }
    }


    @Override
    public String storeFile(InputStream inputStream, long contentLength, String contentType, String fileName) {
        try {
            if (fileName.contains("..")) {
                throw new FileStorageException("File name contains invalid path sequence");
            }

            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(inputStream, targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            throw new FileStorageException("Could not store file " + fileName + ". Please try again later!", ex);
        }
    }

    @Override
    public Resource loadFileAsResource(String fileName) {
        try{
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()){
                return resource;
            }else{
                throw new FileStorageException("File not found" + fileName);
            }
        }catch (MalformedURLException ex){
            throw new FileStorageException("File not found" + fileName);
        }
    }
}

文件的预览和下载接口

   @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);
    }

    /**
     * @Author seam
     * @Description 生成唯一编码
     * @Date 2021/6/25 15:27
     **/
    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);
        String key;
        WsslFileS storageInfo;
        do {
            key = CharUtil.getRandomString(20) + suffix;
            storageInfo = fileService.getEntityByKey(key);
        }
        while (storageInfo != null);
        return key;
    }
posted @ 2022-07-18 09:23  肖恩雷  阅读(891)  评论(0编辑  收藏  举报