Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change originalFilename of MultipartFile

I have a MultipartFile file on server side. I would like to change the original file name of this file, yet the class only support getOriginalFilename().

Can anyone help me with this? PS: It is an image file uploaded.

Thanks alot.

like image 861
Le Kim Trang Avatar asked Mar 10 '16 10:03

Le Kim Trang


People also ask

How do I change the original file name in MultipartFile?

You can't change original name of MultipleFile . But you can save this file with another name, when will pass File to transferTo() method.


1 Answers

You can change the name with MockMultipartFile class. For example, to add a timestamp to multipart file.

MultipartFile multipartFile = new  MockMultipartFile(FilenameUtils.getBaseName(oldMultipartFile.getOriginalFilename()).concat(new SimpleDateFormat("yyyyMMddHHmm").format(new Date())) + "." + FilenameUtils.getExtension(oldMultipartFile.getOriginalFilename()), oldMultipartFile.getInputStream());

and then use multipartFile with new name or you can just rename file before save like this

  String currentDate = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());

  file.getOriginalFilename().replace(file.getOriginalFilename(), FilenameUtils.getBaseName(file.getOriginalFilename()).concat(currentDate) + "." + FilenameUtils.getExtension(file.getOriginalFilename())).toLowerCase())
like image 84
Dave Kraczo Avatar answered Nov 21 '22 07:11

Dave Kraczo