我只是想在 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>