编程语言
首页 > 编程语言> > java下载静态资源文件

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

标签:body,contentType,resolver,静态,下载,ResponseEntity,java,resources,ex
来源: https://www.cnblogs.com/seanRay/p/16489252.html