[英]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.