3

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.

2 Answers 2

2

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(); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am trying to create file within my program, not uploading it. Is there a way to create within java or convert file to multipart within java without loosing data
Multipart is one of the simple way in MVC to upload file. If it is not uploading can u post stack trace . Make sure form is submitting by post and controller method also post.
2

You can create Multipart file using MockMultipartFile in java.

MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.