【问题标题】:how to upload an image using servlet to an absolute path如何使用 servlet 将图像上传到绝对路径
【发布时间】:2012-09-16 13:32:30
【问题描述】:

我想上传一个文件到我的项目文件夹。我的代码如下:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    File savedFile;
    String destination;

    List<FileItem> items = null;
    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
        } else {
            // Process form file field (input type="file").
            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());
            InputStream fileContent = item.getInputStream();

            String userName = (String) session.getAttribute("newUser");

            destination = getServletConfig().getServletContext().getContextPath() + "\\" + userName + ".jpeg";
            savedFile = new File(destination);

            //Check if file exists
            if(!savedFile.exists()) 
                savedFile.createNewFile();

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));
            byte[] buffer = new byte[1024];
            int len;

            //Read from file and write to new file destination
            while((len = fileContent.read(buffer)) >= 0) {
                bos.write(buffer, 0, len);
            }

            //Closing the streams
            fileContent.close();
            bos.close();

        }
    }

}

当我运行 jsp 文件并浏览并选择所需的图像并提交表单时,servlet 运行但它抛出 IOException。异常是由我使用 savedFile.createNewFile() 创建新路径的行引发的。在我使用该代码之前,它引发了另一个 FileNotFoundException。我不确定我提供的路径是否正确。

【问题讨论】:

    标签: image jsp servlets apache-commons


    【解决方案1】:

    尝试使用getRealPath()方法。

     String fileName="/" + userName + ".jpeg";
     destination = getServletContext().getRealPath(fileName);
     savedFile = new File(destination);
    

    【讨论】:

    • userName 是我从返回 null 的会话对象访问的字符串值。它的值是在另一个 servlet 中设置的,但我不确定它为什么返回 null。会不会是编码类型的影响?但是会话对象应该在整个会话期间仍然可用。不是吗?
    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多