Java 文件上载到错误的目录
我希望文件(用户头像图片)上传到Java 文件上载到错误的目录,java,jsp,servlet-3.0,Java,Jsp,Servlet 3.0,我希望文件(用户头像图片)上传到myproject/src/webapp/WEB-INF/upload/avatars,但它们是在C:/WEB-INF/upload/avatars中上传的。不幸的是,我无法将这些位于C:/directory中的图片显示到jsp页面。 那么,我的代码有什么问题?这种做法也被认为是理想的吗?谢谢 String format = null; String fileName = null; String userName
myproject/src/webapp/WEB-INF/upload/avatars
,但它们是在C:/WEB-INF/upload/avatars
中上传的。不幸的是,我无法将这些位于C:/directory中的图片显示到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>
存储上传的化身的位置
文件上传
/WEB-INF/上传/化身
您可能需要使用ServletContext.getRealPath()
将路径映射到应用程序的本地文件夹
这是因为web应用程序在web服务器上的虚拟路径下运行
有关更多信息,请参阅文档页面