Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 文件上载到错误的目录_Java_Jsp_Servlet 3.0 - Fatal编程技术网

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服务器上的虚拟路径下运行

有关更多信息,请参阅文档页面