springboot返回静态文件内容与下载静态文件
2021-09-14 14:03:18
@ResponseBody @RequestMapping("/robots.txt") private ResponseEntity<Resource> robots() { try { String fileName = "robots.txt"; String filePath = "static/robots.txt"; /** * jar包内相对路径,如static文件夹robots.txt,路径为:static/robots.txt */ ClassPathResource resource = new ClassPathResource(filePath); // 获取本地文件系统中的文件资源 /** * 绝对路径,如 D:\chenanlian\yinji\officialsite\src\main\resources\static\robots.txt */ // FileSystemResource resource = new FileSystemResource(filePath); // 解析文件的 mime 类型 String mediaTypeStr = URLConnection.getFileNameMap().getContentTypeFor(fileName); // 无法判断MIME类型时,作为流类型 mediaTypeStr = (mediaTypeStr == null) ? MediaType.APPLICATION_OCTET_STREAM_VALUE : mediaTypeStr; // 实例化MIME MediaType mediaType = MediaType.parseMediaType(mediaTypeStr); /* * 构造响应的头 */ HttpHeaders headers = new HttpHeaders(); headers.setContentType(mediaType); // 如果是下载,则加上下面两行;如果是直接返回文件内容,则不需要,下载之后需要在请求头中放置文件名,该文件名按照ISO_8859_1编码。 // 获取文件名称,中文可能被URL编码 // String filenames = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); // headers.setContentDispositionFormData("attachment", filenames); /* * 返还资源 */ return ResponseEntity.ok() .headers(headers) .contentLength(resource.getInputStream().available()) .body(resource); } catch (IOException e) { return ResponseEntity.status(404).build(); } }