无法使用Apache fileupload库在服务器中保存文件类型

时间:2012-09-05 08:37:16

标签: java jsp servlets

我只是尝试在jsp中使用type = file上传任何文件,然后尝试使用Servlet保存在服务器中。

doPost方法中的Servlet代码如下所示

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    System.out.println(" isMultipart ="+isMultipart);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
           System.out.println(" inside iterator..is form field"+item.isFormField());




                if (!item.isFormField()) {
                    String fileName = item.getName();

                    System.out.println(" inside nor form field");
                    String root1 = getServletContext().getRealPath("/");

                    System.out.println(" server root ="+root1);
                    File path = new File(root + "/uploads");
                    if (!path.exists()) {
                        boolean status = path.mkdirs();

                        System.out.println(" inside path doesnt exist");
                    } // if file path doesnt exists

                    File uploadedFile = new File(path + "/" + fileName);
                    System.out.println(uploadedFile.getAbsolutePath());
                    item.write(uploadedFile);
                } // if condition for field not form field but file
            } // while more files per request
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

在线if (!item.isFormField())它不在里面。即使在jsp中,我已经将正确的enctype设置如下

<form action="Test" enctype="multipart/form-data" method="post">
<label for="fil">Please select file</label>
<input id="fil" type="file">
<input type="submit" name="click" value="click">

</form>

1 个答案:

答案 0 :(得分:0)

得到了解决。在输入像<input id="fil" type="file" name="file" >之类的名称属性之后,问题就解决了。