org.springframework.http.ContentDisposition Java Examples

The following examples show how to use org.springframework.http.ContentDisposition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StandardMultipartHttpServletRequest.java    From spring-analysis-note with MIT License 10 votes vote down vote up
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size());
		for (Part part : parts) {
			String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
			ContentDisposition disposition = ContentDisposition.parse(headerValue);
			String filename = disposition.getFilename();
			if (filename != null) {
				if (filename.startsWith("=?") && filename.endsWith("?=")) {
					filename = MimeDelegate.decode(filename);
				}
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Throwable ex) {
		handleParseFailure(ex);
	}
}
 
Example #2
Source File: StandardMultipartHttpServletRequest.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size());
		for (Part part : parts) {
			String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
			ContentDisposition disposition = ContentDisposition.parse(headerValue);
			String filename = disposition.getFilename();
			if (filename != null) {
				if (filename.startsWith("=?") && filename.endsWith("?=")) {
					filename = MimeDelegate.decode(filename);
				}
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Throwable ex) {
		handleParseFailure(ex);
	}
}
 
Example #3
Source File: ResourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void shouldReadImageResource() throws IOException {
	byte[] body = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("logo.jpg"));
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
	inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG);
	inputMessage.getHeaders().setContentDisposition(
			ContentDisposition.builder("attachment").filename("yourlogo.jpg").build());
	Resource actualResource = converter.read(Resource.class, inputMessage);
	assertThat(FileCopyUtils.copyToByteArray(actualResource.getInputStream()), is(body));
	assertEquals("yourlogo.jpg", actualResource.getFilename());
}
 
Example #4
Source File: ResourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-13443
public void shouldReadInputStreamResource() throws IOException {
	try (InputStream body = getClass().getResourceAsStream("logo.jpg") ) {
		MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
		inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG);
		inputMessage.getHeaders().setContentDisposition(
				ContentDisposition.builder("attachment").filename("yourlogo.jpg").build());
		Resource actualResource = converter.read(InputStreamResource.class, inputMessage);
		assertThat(actualResource, instanceOf(InputStreamResource.class));
		assertThat(actualResource.getInputStream(), is(body));
		assertEquals("yourlogo.jpg", actualResource.getFilename());
	}
}
 
Example #5
Source File: ResourceHttpMessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void shouldReadImageResource() throws IOException {
	byte[] body = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("logo.jpg"));
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
	inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG);
	inputMessage.getHeaders().setContentDisposition(
			ContentDisposition.builder("attachment").filename("yourlogo.jpg").build());
	Resource actualResource = converter.read(Resource.class, inputMessage);
	assertThat(FileCopyUtils.copyToByteArray(actualResource.getInputStream()), is(body));
	assertEquals("yourlogo.jpg", actualResource.getFilename());
}
 
Example #6
Source File: ResourceHttpMessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-13443
public void shouldReadInputStreamResource() throws IOException {
	try (InputStream body = getClass().getResourceAsStream("logo.jpg") ) {
		MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
		inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG);
		inputMessage.getHeaders().setContentDisposition(
				ContentDisposition.builder("attachment").filename("yourlogo.jpg").build());
		Resource actualResource = converter.read(InputStreamResource.class, inputMessage);
		assertThat(actualResource, instanceOf(InputStreamResource.class));
		assertThat(actualResource.getInputStream(), is(body));
		assertEquals("yourlogo.jpg", actualResource.getFilename());
	}
}
 
Example #7
Source File: ReactiveS3ApplicationLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private void addFileEntity(String name, MultiValueMap<String, Object> body, File file) throws Exception {

        byte[] data = Files.readAllBytes(file.toPath());
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        ContentDisposition contentDispositionHeader = ContentDisposition.builder("form-data")
          .name(name)
          .filename(file.getName())
          .build();
        
        headers.add(HttpHeaders.CONTENT_DISPOSITION, contentDispositionHeader.toString());
        
        HttpEntity<byte[]> fileEntity = new HttpEntity<>(data, headers);
        body.add(name, fileEntity);
    }
 
Example #8
Source File: DownloadController.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
@GetMapping
public ResponseEntity<Resource> handleRequest(Principal p,
        @RequestParam Optional<Integer> id,
        @RequestParam(required = false) Integer playlist,
        @RequestParam(required = false) Integer player,
        @RequestParam(required = false, name = "i") List<Integer> indices,
        ServletWebRequest swr) throws Exception {
    User user = securityService.getUserByName(p.getName());
    Player transferPlayer = playerService.getPlayer(swr.getRequest(), swr.getResponse(), false, false);
    String defaultDownloadName = null;
    ResponseDTO response = null;

    Supplier<TransferStatus> statusSupplier = () -> statusService.createDownloadStatus(transferPlayer);

    Consumer<TransferStatus> statusCloser = status -> {
        statusService.removeDownloadStatus(status);
        securityService.updateUserByteCounts(user, 0L, status.getBytesTransferred(), 0L);
        LOG.info("Transferred {} bytes to user: {}, player: {}", status.getBytesTransferred(), user.getUsername(), transferPlayer);
    };

    MediaFile mediaFile = id.map(mediaFileService::getMediaFile).orElse(null);

    if (mediaFile != null) {
        if (!securityService.isFolderAccessAllowed(mediaFile, user.getUsername())) {
            throw new AccessDeniedException("Access to file " + mediaFile.getId() + " is forbidden for user " + user.getUsername());
        }

        if (mediaFile.isFile()) {
            response = prepareResponse(Collections.singletonList(mediaFile), null, statusSupplier, statusCloser, Collections.emptyList());
            defaultDownloadName = mediaFile.getFile().getFileName().toString();
        } else {
            response = prepareResponse(mediaFileService.getChildrenOf(mediaFile, true, false, true), indices,
                    statusSupplier, statusCloser, indices == null ? Collections.singletonList(mediaFile.getCoverArtFile()) : Collections.emptyList());
            defaultDownloadName = FilenameUtils.getBaseName(mediaFile.getPath()) + ".zip";
        }
    } else if (playlist != null) {
        response = prepareResponse(playlistService.getFilesInPlaylist(playlist), indices, statusSupplier, statusCloser, Collections.emptyList());
        defaultDownloadName = playlistService.getPlaylist(playlist).getName() + ".zip";
    } else if (player != null) {
        response = prepareResponse(transferPlayer.getPlayQueue().getFiles(), indices, statusSupplier, statusCloser, Collections.emptyList());
        defaultDownloadName = "download.zip";
    }

    if (swr.checkNotModified(String.valueOf(response.getSize()), response.getChanged())) {
        return null;
    }

    String filename = Optional.ofNullable(response.getProposedName()).orElse(defaultDownloadName);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentDisposition(ContentDisposition.builder("attachment").filename(filename, StandardCharsets.UTF_8).build());
    headers.setContentType(MediaType.parseMediaType(StringUtil.getMimeType(FilenameUtils.getExtension(filename))));
    LOG.info("Downloading '{}' to {}", filename, player);
    return ResponseEntity.ok().headers(headers).body(response.getResource());
}