John P
John P

Reputation: 1221

Java send ByteArray as a param to a method which expects MultipartFile

Lets say I have a method sendFile(MultipartFile file) and I want to send a ByteArray file as a param

ByteArray file = ...
ByteArrayResource bar = new ByteArrayResource(file)
sendFile(bar)

I have converted the ByteArray to ByteArrayResource and sending it to the method expecting MultipartFile, but I get a compilation error:

Type mismatch. Required: MultipartFile, Found: ByteArrayResource

Why am I getting this error?

This is the hierarchy of the MultipartFile interface:

MultipartFile -> InputStreamSource -> ByteArrayResource

Upvotes: 0

Views: 594

Answers (1)

lane.maxwell
lane.maxwell

Reputation: 5893

First, if your method takes a MultipartFile, you must send it a MultipartFile or another class that IS a MultipartFile. A ByteArrayResource IS NOT a MultipartFile, but a MultipartFile HAS a ByteArrayResource. Read up on the distinction between HAS-A vs. IS-A.

Also, since presumably you wrote the sendFile method, why not overload it and create a version that takes a ByteArrayResource?

If you must use a MultipartFile, you'll need to create one to send to this method.

MultipartFile multipartFile = new MockMultipartFile("arbitrayFileName", bas.getByteArray());

Upvotes: 0

Related Questions