【发布时间】:2015-11-12 14:15:49
【问题描述】:
我希望文件(用户头像图片)上传到 myproject/src/webapp/WEB-INF/upload/avatars,但他们正在上传到 C:/WEB-INF/upload/avatars。不幸的是,我无法将位于 C:/ 目录中的这些图片显示到 jsp 页面。
那么,我的代码有什么问题?这种做法也被认为是理想的吗?谢谢
String format = null;
String fileName = null;
String userName = userService.getLoggedInUsername();
byte[] bytes = file.getBytes();
// Get file extension
fileName = file.getOriginalFilename();
int index = fileName.lastIndexOf(".");
if(index > 0){
format = fileName.substring(index+1);
format = format.toLowerCase();
}
// Creating the directory to store file
String uploadPath = request.getSession().getServletContext().getInitParameter("file-upload");
File dir = new File(uploadPath);
if (!dir.exists())
dir.mkdirs();
// Create the file on server
String filePath = uploadPath + File.separator + userName + "." + format;
File serverFile = new File(filePath);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
// Update photo path in db
User user = new User();
user.setUserName(userName);
user.setUserPhotoPath(filePath);
userService.insertPhotoPath(user);
web.xml 参数:
<context-param>
<description>Location to store uploaded avatars</description>
<param-name>file-upload</param-name>
<param-value>
/WEB-INF/upload/avatars
</param-value>
</context-param>
【问题讨论】:
标签: java jsp servlet-3.0