This answer 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:
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.