Deprecated as of 4.3.13, in favor of selective use of ClassPathResource.ClassPathResource(String, ClassLoader) vs ClassPathResource.ClassPathResource(String, Class)
private int contentLength() throws IOException { return (int) new ClassPathResource("do_not_delete_me.txt").contentLength(); }
@Test // SPR-15041 public void applicationOctetStreamDefaultContentType() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); ClassPathResource body = Mockito.mock(ClassPathResource.class); BDDMockito.given(body.getFilename()).willReturn("spring.dat"); BDDMockito.given(body.contentLength()).willReturn(12L); BDDMockito.given(body.getInputStream()).willReturn(new ByteArrayInputStream("Spring Framework".getBytes())); HttpRange range = HttpRange.createByteRange(0, 5); ResourceRegion resourceRegion = range.toResourceRegion(body); converter.write(Collections.singletonList(resourceRegion), null, outputMessage); assertThat(outputMessage.getHeaders().getContentType(), is(MediaType.APPLICATION_OCTET_STREAM)); assertThat(outputMessage.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE), is("bytes 0-5/12")); assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Spring")); }
@RequestMapping(value = "/get/doc" , method = RequestMethod.GET , produces = "application/msword") public ResponseEntity<InputStreamResource> getProposalDocs() throws IOException{ ClassPathResource docfile = new ClassPathResource("file.doc"); HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity.ok() .headers(headers) .contentLength(docfile.contentLength()) .contentType(MediaType.parseMediaType("application/msword")) .body(new InputStreamResource(docfile.getInputStream())); }
@RequestMapping(value = "/download", method = RequestMethod.GET) @ApiOperation(value = "文件下載", httpMethod = "GET", response = byte.class) @ApiImplicitParams({ @ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "query"), @ApiImplicitParam(name = "fileType", value = "文件类型", paramType = "query") }) public ResponseEntity<InputStreamResource> downloadFile(String fileName, String fileType) throws IOException { String filePath = fileName+"."+fileType; ClassPathResource file = new ClassPathResource("down/"+filePath); HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename())); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity .ok() .headers(headers) .contentLength(file.contentLength()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new InputStreamResource(file.getInputStream())); } }