I am trying to use create Multipart files and upload these files using my Java Spring MVC web application. I could not find any documentation to create a multipart file using Java, so I tried to create a file and then convert it to a multipart file and then upload it. I use the following code:
int randomCode = randomCodeGenerator() ;
File file1 = new File("E:\\myAccount\\voice"+randomCode+".xml");
FileWriter writer = new FileWriter(file1);
writer.write(response);
writer.close();
I am then trying to convert it into a multipart file as follows:
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file1.getName(), (int) file1.length() , file1.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
byte[] `filedata` = multipartFile.getBytes();
Now I always get the filedata as 0, which means the multipart file is empty. but I have already written to the file before converting it into multipart.
I am not sure what I am missing here. Also, I am not sure this approach will work on my server since I am trying to create a file on my disk, which is working for me locally. Is there any way to create a multipart file or convert the file to Multipart file without losing data.
If you upload like that then file will read from local and it will not read when u check-in or run from server.
Use common Multipart or standard Multipart resolver which may solve your issue.
Refer below code.
JSP
method="POST" enctype="multipart/form-data">
Controller:
Multipart upload;
byte[] bytes = file.getBytes();
Path path=file.get(fileinputstream (upload));
Bean:
private Multipart upload;
Getter and setter method;
Register Bean
@Bean public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With