Reputation:
How can I convert a MultipartFile
to FileInputStream
in memory?
I have tried to below , but i am facing the error as
org.springframework.web.multipart.commons.CommonsMultipartFile cannot be cast to java.io.File
My Code is
FileInputStream fis = new FileInputStream((File)file);
where file is a multipart file
Upvotes: 17
Views: 85257
Reputation: 71
String filename = file.getOriginalFilename();
Random val = new Random();
int randomNumber = val.nextInt(999999);
String filePath = path + File.separator + randomNumber+filename;
file.transferTo(Paths.get(filePath));
Note: Generate the appropriate file-sending destination path and use the Multipartfile object file.transfterTo() method. its alternative of copy()
the copy method makes me at runtime error, so the best way to copy and store your image use the file.transferTo() object.
Upvotes: 0
Reputation: 79
We may just cast and use like below
FileInputStream file = (FileInputStream) multipartFile.getInputStream();
Upvotes: 0
Reputation: 245
To convert Multipart file to Input Stream
MultipartFile file;
InputStream inputStream = new InputStream(file.getInputStream());
This worked for me.
Upvotes: 0
Reputation: 41
Try using:
MultipartFile uploadedFile = ((MultipartHttpServletRequest)request).getFile('file_name')
InputStream inputStream = new ByteArrayInputStream(uploadedFile?.getBytes())
Upvotes: 4
Reputation: 25
For a multipart file eg:
FileMultipartData part = new FileMultipartData();
InputStream inputStream = part.getFileMultipart().get(0).getByteStream();
This worked for me in my code. Please try it
Upvotes: -2
Reputation: 1067
You can't create an instance of FileInputStream unless your file is not on file system.
You have to either first save the multipart file in temporary location on server using
file.transferTo(tempFile);
InputStream stream = new FileInputStream(tempFile);
But multipart file can also be read simply via basic streams methods such as
InputStream inputStream = new BufferedInputStream(file.getInputStream());
Upvotes: 35
Reputation: 3154
Take look at MultipartFile
In that you can go with :
void transferTo(File dest)
This method transfer the received file to the given destination file.
Upvotes: 1