I have to upload an image from the user interface and change its name according to my need.
ie if user uploads an image with a name WIN_20151122_09_57_47_Pro.jpg I would have to change it to 1.jpg
I am using Spring mvc and for file upload and display I am using MultiPartFile
datatype
Below is the model.
FileBucket.java
package com.faisal.model;
import org.springframework.web.multipart.MultipartFile ;
public class FileBucket {
MultipartFile file ;
public MultipartFile getFile() {
return file ;
}
public void setFile(MultipartFile file ) {
this.file = file;
}
}
The controller part where I am uploading the file on the server
@Autowired
ServletContext servletContext;
@RequestMapping(value = "/singleUpload" , method = RequestMethod.POST)
public String singleFileUpload(@Valid FileBucket fileBucket,
BindingResult result, ModelMap model ) throws IOException {
String PROFILE_UPLOAD_LOCATION = servletContext.getRealPath("/" )
+ File. separator + "resources" + File.separator
+ "profile_images" + File.separator;
if (result .hasErrors()) {
System. out.println("validation errors" );
return "singleFileUploader" ;
} else {
System. out.println("Fetching file" );
String destination=PROFILE_UPLOAD_LOCATION
+ fileBucket.getFile().getOriginalFilename();
File file = new File(destination);
File newFile=new File(PROFILE_UPLOAD_LOCATION +"1.jpg" );
FileCopyUtils. copy(fileBucket.getFile().getBytes(), file);
FileUtils. moveFile(file, newFile);
MultipartFile multipartFile = fileBucket .getFile();
String fileName = multipartFile .getOriginalFilename();
model.addAttribute("fileName" , fileName );
return "success" ;
}
}
View page
<body>
<div class="success" >
<img src=" ${pageContext.request.contextPath}/resources/profile_images/${fileName} " height ="100" width="100" />
<br/>
File <strong> ${fileName}</strong > uploaded successfully.
</div>
</body>
In the code above I have successfully renamed the file but then while redirecting on the same page the image is not displayed since it has been replaced by 1.jpg
Try <spring:url>
like this <img src='<spring:url value="/resources/profile-pictures/${user.profileImage}" />' >
.
Here's how I implemented UserController and in jsp view <img src='<spring:url value="/resources/profile-pictures/${user.profileImage}" />' alt="User Image">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.