如何使用servlet将图像上传到绝对路径

时间:2012-09-25 04:07:56

标签: image jsp servlets apache-commons

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

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。我不确定我提供的路径是否正确。

1 个答案:

答案 0 :(得分:2)

尝试使用getRealPath()方法。

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