[英]Rename file while uploading on webapp in spring using MultiPartFile datatype
我必须从用户界面上传图像并根据需要更改其名称。
即如果用户上传名称为 WIN_20151122_09_57_47_Pro.jpg 的图像,我将不得不将其更改为 1.jpg
我正在使用 Spring mvc 和文件上传和显示我使用MultiPartFile
数据类型
下面是模型。
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;
}
}
我在服务器上上传文件的控制器部分
@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" ;
}
}
查看页面
<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>
在上面的代码中,我成功地重命名了文件,但是在同一页面上重定向时,图像没有显示,因为它已被 1.jpg 替换
像这样尝试<spring:url>
<img src='<spring:url value="/resources/profile-pictures/${user.profileImage}" />' >
。
这是我如何实现UserController并在 jsp 视图中<img src='<spring:url value="/resources/profile-pictures/${user.profileImage}" />' alt="User Image">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.