MockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
originalFileName, contentType, content);
Answer from Arun on Stack OverflowMockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
originalFileName, contentType, content);
File file = new File("src/test/resources/input.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file",
file.getName(), "text/plain", IOUtils.toByteArray(input));
Java spring: best way to convert a File to a MultipartFile - Stack Overflow
java - Converting File to MultiPartFile with spring - Stack Overflow
Best way to convert Inputstream to Multipartfile
spring mvc - How to convert byte array to MultipartFile - Stack Overflow
Videos
InputStream stream = new FileInputStream(file)
multipartFileToSend = new MockMultipartFile("file", file.getName(), MediaType.TEXT_HTML_VALUE, stream);
try this
I propose this method which allows converting a File to a MultipartFile:
public static MultipartFile buildMultipartFile(@NonNull final File file,
@NonNull final String multipartFileParameterName) throws IOException {
MultipartFile multipartFile = null;
try (final FileInputStream input = new FileInputStream(file)) {
multipartFile = new MockMultipartFile(
multipartFileParameterName,
file.getName(),
Files.probeContentType(file.toPath()),
IOUtils.toByteArray(input));
}
return multipartFile;
}
File file = new File("src/test/resources/input.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file",
file.getName(), "text/plain", IOUtils.toByteArray(input));
This is another way of getting multipart file from File object
File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
You need the
fileItem.getOutputStream();
because it will throw NPE otherwise.
I want to send ByteArrayInputStream in a request to different service which accepts a MultiPartFile. Is there a better way than implementing the MultiPartFile interface? MockMultiPartFile is for testing only, right?
org.springframework.web.multipart.MultipartFile is an interface so firstly you are going to need to work with an implementation of this interface.
The only implementation that I can see for that interface that you can use out-of-the-box is org.springframework.web.multipart.commons.CommonsMultipartFile. The API for that implementation can be found here
Alternatively as org.springframework.web.multipart.MultipartFile is an interface, you could provide your own implementation and simply wrap your byte array. As a trivial example:
/*
*<p>
* Trivial implementation of the {@link MultipartFile} interface to wrap a byte[] decoded
* from a BASE64 encoded String
*</p>
*/
public class BASE64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;
public BASE64DecodedMultipartFile(byte[] imgContent) {
this.imgContent = imgContent;
}
@Override
public String getName() {
// TODO - implementation depends on your requirements
return null;
}
@Override
public String getOriginalFilename() {
// TODO - implementation depends on your requirements
return null;
}
@Override
public String getContentType() {
// TODO - implementation depends on your requirements
return null;
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(imgContent);
}
}
This question has already been answered above. Recently i was working on the requirement to convert byte array object to multipartfile object. There are two ways to achieve this.
Approach 1:
Use the default CommonsMultipartFile where you to use the FileDiskItem object to create it.
Example:
FileItem fileItem = new DiskFileItem("fileData", "application/pdf",true, outputFile.getName(), 100000000, new java.io.File(System.getProperty("java.io.tmpdir")));
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
Approach 2:
Create your own custom multipart file object and convert the byte array to multipartfile.
public class CustomMultipartFile implements MultipartFile {
private final byte[] fileContent;
private String fileName;
private String contentType;
private File file;
private String destPath = System.getProperty("java.io.tmpdir");
private FileOutputStream fileOutputStream;
public CustomMultipartFile(byte[] fileData, String name) {
this.fileContent = fileData;
this.fileName = name;
file = new File(destPath + fileName);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
fileOutputStream = new FileOutputStream(dest);
fileOutputStream.write(fileContent);
}
public void clearOutStreams() throws IOException {
if (null != fileOutputStream) {
fileOutputStream.flush();
fileOutputStream.close();
file.deleteOnExit();
}
}
@Override
public byte[] getBytes() throws IOException {
return fileContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(fileContent);
}
}
This how you can use above CustomMultipartFile object.
String fileName = "intermediate.pdf";
CustomMultipartFile customMultipartFile = new CustomMultipartFile(bytea, fileName);
try {
customMultipartFile.transferTo(customMultipartFile.getFile());
} catch (IllegalStateException e) {
log.info("IllegalStateException : " + e);
} catch (IOException e) {
log.info("IOException : " + e);
}
This will create the required PDF and store that into
java.io.tmpdir with the name intermediate.pdf
Thanks.
Hi!
I am trying to convert a string that is a URL from a PDF to a File, and then that file to a MultiPartFile.
This is the code I am using to create the MultiPartFile.
File file = new File(fileName);
try (final FileInputStream input = new FileInputStream(file)) {
multipartFile = new MockMultipartFile(
fileName,
file.getName(),
String.valueOf(MediaType.APPLICATION_PDF),
IOUtils.toByteArray(input));
}
This seems to generate the MultiPartFile fine, but then it uploads to a bucket in s3, and when I try to open it I can't, it just says it can't be opened. But idk if this is a problem when generating the MultiPartFile or uploading it to s3. It doesn't break when generating it or uploading it, only when I try to open it from aws, it tries to load but it says "We cant open this file".
Does anyone know what I could be doing wrong, or what I could try? Thank you very much!