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

原创文章,作者:Carrie001128,如若转载,请注明出处:https://blog.ytso.com/275127.html

(0)
上一篇 2022年7月18日
下一篇 2022年7月18日

相关推荐

发表回复

登录后才能评论