Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Can't import org.springframework.mock.web.MockMultipartFile outside of testing classes

Writer Mia Lopez

I'm trying to turn an image stored as a Blob in my DB into a MultipartFile to serve back to the client when it's requested. I retrieve the Blob as a byte[] and I'm trying to convert it into a MultipartFile to serve back to the client

I'm trying to do it this way :

But IntelliJ is telling me it can't find the MockMultipartFile part when I do the import of: import org.springframework.mock.web.MockMultipartFile
I can import this in a test class no problem, but not outside of the test class. Can I do it here?

Also, I tried to do this by implementing a class with my own version of MultipartFile as stated in another popular answer, but it's telling me it can't find a serialzer.

Any suggestions?

2

2 Answers

There are couple of issues with your approach.

  1. Multipart file is an HTTP Request format and not intended for response.
  2. For a response all you have to do is write the file to the response.getOutputStream(). Which becomes way easier using Spring

Now coming to your original question that you can't import MockMultipartFile. That's most likely because you're using Maven and the dependency (most likely spring-boot-starter-test) has scope set to test.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope><!-- CHANGE THIS TO "runtime" -->
</dependency>

But again as I said before, there's no need to do that. You don't have to consider the Multipart when you're providing a response, it's a protocol to upload files.

Here's how you can provide a download link to a Blob in Spring

@GetMapping(path = "download")
public ResponseEntity<Resource> download(String param) throws IOException { InputStreamResource resource = new InputStreamResource(/* InputStream of blob */); long fileLength = /*Length of content, bytes.length or something */ return ResponseEntity.ok() .contentLength(fileLength) .contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE) .body(resource);
}
6

Finally the package i found which helped with import org.springframework.mock.web.MockMultipartFile;

<properties> <java.version>1.8</java.version> <spring.version>5.1.2.RELEASE</spring.version>
</properties>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version>
</dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version>
</dependency>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.