Java Code Examples for org.springframework.http.codec.multipart.FilePart

The following examples show how to use org.springframework.http.codec.multipart.FilePart. These examples are extracted from open source projects. 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 Project: jetlinks-community   Source File: CertificateController.java    License: Apache License 2.0 6 votes vote down vote up
@SaveAction
@PostMapping("/upload")
@SneakyThrows
public Mono<String> upload(@RequestPart("file") Part part) {

    if (part instanceof FilePart) {
        return (part)
                .content()
                .collectList()
                .flatMap(all -> Mono.fromCallable(() ->
                        Base64.encodeBase64String(StreamUtils.copyToByteArray(factory.join(all).asInputStream()))))
                ;
    } else {
        return Mono.error(() -> new IllegalArgumentException("[file] part is not a file"));
    }

}
 
Example 2
Source Project: jetlinks-community   Source File: SerializableAccessLog.java    License: Apache License 2.0 6 votes vote down vote up
public static SerializableAccessLog of(AccessLoggerInfo info) {
    SerializableAccessLog accessLog = FastBeanCopier.copy(info, new SerializableAccessLog(), "parameters", "method", "target", "exception");
    accessLog.setMethod(info.getMethod().getName());
    accessLog.setTarget(info.getTarget().getName());
    accessLog.setException(info.getException() == null ? ""
            : StringUtils.throwable2String(info.getException()));
    Map<String, Object> newParameter = info.getParameters()
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> {
                Object value = e.getValue();
                if (value instanceof FilePart) {
                    return ("file:") + ((FilePart) value).filename();
                }
                return JSON.toJSONString(value);
            }));

    accessLog.setParameters(newParameter);
    return accessLog;
}
 
Example 3
Source Project: java-technology-stack   Source File: MultipartIntegrationTests.java    License: MIT License 6 votes vote down vote up
public Mono<ServerResponse> multipartData(ServerRequest request) {
	return request
			.body(BodyExtractors.toMultipartData())
			.flatMap(map -> {
				Map<String, Part> parts = map.toSingleValueMap();
				try {
					assertEquals(2, parts.size());
					assertEquals("foo.txt", ((FilePart) parts.get("fooPart")).filename());
					assertEquals("bar", ((FormFieldPart) parts.get("barPart")).value());
				}
				catch(Exception e) {
					return Mono.error(e);
				}
				return ServerResponse.ok().build();
			});
}
 
Example 4
Source Project: java-technology-stack   Source File: MultipartIntegrationTests.java    License: MIT License 6 votes vote down vote up
@PostMapping("/requestPart")
void requestPart(
		@RequestPart FormFieldPart fieldPart,
		@RequestPart("fileParts") FilePart fileParts,
		@RequestPart("fileParts") Mono<FilePart> filePartsMono,
		@RequestPart("fileParts") Flux<FilePart> filePartsFlux,
		@RequestPart("jsonPart") Person person,
		@RequestPart("jsonPart") Mono<Person> personMono) {

	assertEquals("fieldValue", fieldPart.value());
	assertEquals("fileParts:foo.txt", partDescription(fileParts));
	assertEquals("Jason", person.getName());

	StepVerifier.create(partFluxDescription(filePartsFlux))
			.consumeNextWith(content -> assertEquals("[fileParts:foo.txt,fileParts:logo.png]", content))
			.verifyComplete();

	StepVerifier.create(filePartsMono)
			.consumeNextWith(filePart -> assertEquals("fileParts:foo.txt", partDescription(filePart)))
			.verifyComplete();

	StepVerifier.create(personMono)
			.consumeNextWith(p -> assertEquals("Jason", p.getName()))
			.verifyComplete();
}
 
Example 5
@Test
public void createImageShouldWork() {
	// given
	Image alphaImage = new Image("1", "alpha.jpg");
	Image bravoImage = new Image("2", "bravo.jpg");
	given(repository.save(new Image(any(), alphaImage.getName()))).willReturn(Mono.just(alphaImage));
	given(repository.save(new Image(any(), bravoImage.getName()))).willReturn(Mono.just(bravoImage));
	given(repository.findAll()).willReturn(Flux.just(alphaImage, bravoImage));
	FilePart file1 = mock(FilePart.class);
	given(file1.filename()).willReturn(alphaImage.getName());
	given(file1.transferTo(any())).willReturn(Mono.empty());
	FilePart file2 = mock(FilePart.class);
	given(file2.filename()).willReturn(bravoImage.getName());
	given(file2.transferTo(any())).willReturn(Mono.empty());

	// when
	Mono<Void> done = imageService.createImage(Flux.just(file1, file2));

	// then
	then(done.block()).isNull();
}
 
Example 6
@Test
public void createImageShouldWork() {
	// given
	Image alphaImage = new Image("1", "alpha.jpg");
	Image bravoImage = new Image("2", "bravo.jpg");
	given(repository.save(new Image(any(), alphaImage.getName()))).willReturn(Mono.just(alphaImage));
	given(repository.save(new Image(any(), bravoImage.getName()))).willReturn(Mono.just(bravoImage));
	given(repository.findAll()).willReturn(Flux.just(alphaImage, bravoImage));
	FilePart file1 = mock(FilePart.class);
	given(file1.filename()).willReturn(alphaImage.getName());
	given(file1.transferTo(any())).willReturn(Mono.empty());
	FilePart file2 = mock(FilePart.class);
	given(file2.filename()).willReturn(bravoImage.getName());
	given(file2.transferTo(any())).willReturn(Mono.empty());

	// when
	Mono<Void> done = imageService.createImage(Flux.just(file1, file2));

	// then
	StepVerifier.create(done)
		.verifyComplete();
}
 
Example 7
@Test
public void createImages() {
	Image alphaImage = new Image("1", "alpha.jpg");
	Image bravoImage = new Image("2", "bravo.jpg");
	FilePart file1 = mock(FilePart.class);
	given(file1.filename()).willReturn(alphaImage.getName());
	given(file1.transferTo(any())).willReturn(Mono.empty());
	FilePart file2 = mock(FilePart.class);
	given(file2.filename()).willReturn(bravoImage.getName());
	given(file2.transferTo(any())).willReturn(Mono.empty());

	List<Image> images = imageService
		.createImage(Flux.just(file1, file2))
		.then(imageService.findAllImages().collectList())
		.block(Duration.ofSeconds(30));

	assertThat(images).hasSize(5);
}
 
Example 8
Source Project: spring-analysis-note   Source File: MultipartIntegrationTests.java    License: MIT License 5 votes vote down vote up
public Mono<ServerResponse> multipartData(ServerRequest request) {
	return request
			.body(BodyExtractors.toMultipartData())
			.flatMap(map -> {
				Map<String, Part> parts = map.toSingleValueMap();
				try {
					assertEquals(2, parts.size());
					assertEquals("foo.txt", ((FilePart) parts.get("fooPart")).filename());
					assertEquals("bar", ((FormFieldPart) parts.get("barPart")).value());
				}
				catch(Exception e) {
					return Mono.error(e);
				}
				return ServerResponse.ok().build();
			});
}
 
Example 9
Source Project: spring-analysis-note   Source File: MultipartIntegrationTests.java    License: MIT License 5 votes vote down vote up
public Mono<ServerResponse> parts(ServerRequest request) {
	return request.body(BodyExtractors.toParts()).collectList()
			.flatMap(parts -> {
				try {
					assertEquals(2, parts.size());
					assertEquals("foo.txt", ((FilePart) parts.get(0)).filename());
					assertEquals("bar", ((FormFieldPart) parts.get(1)).value());
				}
				catch(Exception e) {
					return Mono.error(e);
				}
				return ServerResponse.ok().build();
			});
}
 
Example 10
Source Project: spring-analysis-note   Source File: MultipartIntegrationTests.java    License: MIT License 5 votes vote down vote up
@PostMapping("/requestPart")
void requestPart(@RequestPart FormFieldPart fieldPart,
		@RequestPart("fileParts") FilePart fileParts,
		@RequestPart("jsonPart") Mono<Person> personMono) {

	assertEquals("fieldValue", fieldPart.value());
	assertEquals("fileParts:foo.txt", partDescription(fileParts));

	StepVerifier.create(personMono)
			.consumeNextWith(p -> assertEquals("Jason", p.getName()))
			.verifyComplete();
}
 
Example 11
Source Project: spring-analysis-note   Source File: MultipartIntegrationTests.java    License: MIT License 5 votes vote down vote up
private void assertFooPart(Part part) {
	assertEquals("fooPart", part.name());
	assertTrue(part instanceof FilePart);
	assertEquals("foo.txt", ((FilePart) part).filename());

	StepVerifier.create(DataBufferUtils.join(part.content()))
			.consumeNextWith(buffer -> {
				assertEquals(12, buffer.readableByteCount());
				byte[] byteContent = new byte[12];
				buffer.read(byteContent);
				assertEquals("Lorem Ipsum.", new String(byteContent));
			})
			.verifyComplete();
}
 
Example 12
Source Project: springdoc-openapi   Source File: HelloController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/files", produces = { MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
@Operation(summary = "files")
public Flux<Void> handleFileUpload(
		@RequestPart("files") @Parameter(description = "files",
				content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE))
				Flux<FilePart> filePartFux) throws IOException {
	File tmp = File.createTempFile("tmp", "");
	return filePartFux.flatMap(filePart -> {
		Path path = Paths.get(tmp.toString() + filePart.filename());
		System.out.println(path);
		return filePart.transferTo(path);
	});
}
 
Example 13
Source Project: springdoc-openapi   Source File: HelloController.java    License: Apache License 2.0 5 votes vote down vote up
@Operation(summary = "Parse Resume")
@PostMapping(value = "/parse-resume", produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {
		MediaType.MULTIPART_FORM_DATA_VALUE })
@ApiResponses({ @ApiResponse(responseCode = "400", description = "Invalid input") })
public Mono<String> parse(
		@RequestPart(name = "resumeFile") @Parameter(description = "Resume file to be parsed", content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)) FilePart resumeFile) {
	return null;
}
 
Example 14
Source Project: springdoc-openapi   Source File: HelloController.java    License: Apache License 2.0 5 votes vote down vote up
@Operation(summary = "Parse Resume")
@PostMapping(value = "/parse-resume", produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {
		MediaType.MULTIPART_FORM_DATA_VALUE })
@ApiResponses({ @ApiResponse(responseCode = "400", description = "Invalid input") })
public Mono<String> parse(
		@RequestPart(name = "resumeFile") @Parameter(description = "Resume file to be parsed", content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)) FilePart resumeFile) {
	return null;
}
 
Example 15
Source Project: java-technology-stack   Source File: MultipartIntegrationTests.java    License: MIT License 5 votes vote down vote up
public Mono<ServerResponse> parts(ServerRequest request) {
	return request.body(BodyExtractors.toParts()).collectList()
			.flatMap(parts -> {
				try {
					assertEquals(2, parts.size());
					assertEquals("foo.txt", ((FilePart) parts.get(0)).filename());
					assertEquals("bar", ((FormFieldPart) parts.get(1)).value());
				}
				catch(Exception e) {
					return Mono.error(e);
				}
				return ServerResponse.ok().build();
			});
}
 
Example 16
Source Project: java-technology-stack   Source File: MultipartIntegrationTests.java    License: MIT License 5 votes vote down vote up
private void assertFooPart(Part part) {
	assertEquals("fooPart", part.name());
	assertTrue(part instanceof FilePart);
	assertEquals("foo.txt", ((FilePart) part).filename());

	StepVerifier.create(DataBufferUtils.join(part.content()))
			.consumeNextWith(buffer -> {
				assertEquals(12, buffer.readableByteCount());
				byte[] byteContent = new byte[12];
				buffer.read(byteContent);
				assertEquals("Lorem Ipsum.", new String(byteContent));
			})
			.verifyComplete();
}
 
Example 17
/**
 * upload handler method, mapped to POST. Like any file upload handler it consumes MULTIPART_FORM_DATA.
 * Produces a JSON respomse
 *
 * @param parts a flux providing all part contained in the MULTIPART_FORM_DATA request
 * @return a flux of results - one element per uploaded file
 */
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Flux<String> uploadHandler(@RequestBody Flux<Part> parts) {
    return parts
            .filter(part -> part instanceof FilePart) // only retain file parts
            .ofType(FilePart.class) // convert the flux to FilePart
            .flatMap(this::saveFile); // save each file and flatmap it to a flux of results
}
 
Example 18
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 19
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 20
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 21
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy");

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 22
@PostMapping(API_BASE_PATH + "/images")
Mono<Void> create(@RequestPart Flux<FilePart> images) {
	return images
		.map(image -> {
			log.info("We will save " + image +
				" to a Reactive database soon!");
			return image;
		})
		.then();
}
 
Example 23
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy");

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 24
@PostMapping(API_BASE_PATH + "/images")
Mono<Void> create(@RequestPart Flux<FilePart> images) {
	return images
		.map(image -> {
			log.info("We will save " + image +
				" to a Reactive database soon!");
			return image;
		})
		.then();
}
 
Example 25
@PostMapping(value = BASE_PATH)
public Mono<String> createFile(
		@RequestPart("file") Flux<FilePart> files,
		@AuthenticationPrincipal Principal principal) {
	return imageService.createImage(files, principal)
		.then(Mono.just("redirect:/"));
}
 
Example 26
public Mono<Void> createImage(Flux<FilePart> files,
							  Principal auth) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename(),
					auth.getName()))
				.log("createImage-save");
			// end::metric-2[]

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 27
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 28
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 29
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 30
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy")
				.then(Mono.fromRunnable(() ->
					meterRegistry
						.summary("files.uploaded.bytes")
						.record(Paths.get(UPLOAD_ROOT, file.filename()).toFile().length())
				));

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}