如果你想存儲在您的應用程序資源文件夾的圖像,試試這個:
A.資源映射(這個文件夾內的所有目錄將可以訪問):
<mvc:resources location="/resources/" mapping="/resources/**"/>
B.將此加入到jsp頁面中:
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<img src="<spring:url value='/resources/profile-pictures/${user.profileImage}'/>" class="img-circle" alt="User Image">
注意:所有上傳的圖像將被存儲在src\main\webapp\resources\profile-pictures
目錄下。
C.禁用安全:
<http pattern="/resources/**" security="none"/>
D.方法來保存圖片:
@RequestMapping(value="/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("imageFile") MultipartFile file, Principal principal) {
String webappRoot = servletContext.getRealPath("/");
String LoggedInUser = principal.getName();
User user = userService.findLoggedInUser(LoggedInUser);
//System.out.println(user.toString());
try {
if (!file.isEmpty()) {
BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
File destination = new File(webappRoot + "/resources/profile-pictures/ProfileImage"+user.getName()+".jpg"); // something like C:/Users/tom/Documents/nameBasedOnSomeId.png
ImageIO.write(src, "png", destination);
System.out.println("users profile Pic is stored at "+user.getProfileImage() + "UserPassword :" +user.getPassword());
user.setProfileImage("ProfileImage"+user.getName()+".jpg");
userService.update(user);
System.out.println("Image is stored at "+ user.getProfileImage());
}
} catch (Exception e) {
System.out.println("Exception occured" + e.getMessage());
return "redirect:/account/upload?success=false";
}
return "redirect:/account/upload?success=true";
}
PS:這不是理想的解決方案,而是適用於學習的目的。我也在尋找免費的圖像存儲。我遇到了Amazon S3,但它需要信用卡,然後是Box,Dropbox。但我發現這個Cloudinary很有趣。
PPS:您可以看到我的演示應用程序here。