这应该是一个非常简单的程序,但是花了我一些时间来弄清楚如何使用Apache commons FileUpload组件。由于没有人会读到此,因此我将其放在此处仅供参考。请注意如何将上传的文件保存到服务器。Form的HTML代码太简单了,无法在任何地方找到,因此以下仅是servlet中doPost方法的代码。
protected void doPost(HttpServletRequest res, HttpServletResponse response)
throws ServletException, IOException {
// Commons文件上载类专门实例化
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
ServletOutputStream out = null;
try {
//解析传入的HTTP请求
// Commons接管传入的请求
// //获取所有已发送数据的迭代器
List items = upload.parseRequest(res);
Iterator iter = items.iterator();
//设置响应内容类型
response.setContentType("text/html");
//设置返回XML数据
out = response.getOutputStream();
//迭代通过传入的请求数据
while (iter.hasNext()) {
//获取在迭代的当前项
FileItem item = (FileItem) iter.next();
//如果当前项是一个HTML表单字段
if (item.isFormField()) {
//返回与字段名称和值的XML节点 value
out.println("this is a form data " + item.getFieldName() + "<br>");
// //如果当前项是文件数据
} else {
// Specify where on disk to write the file
// Using a servlet init param to specify location on disk
// Write the file data to disk
// TODO: Place restrictions on upload data
File disk = new File("C:\\uploaded_files\\"+item.getName());
item.write(disk);
//返回带有文件名和大小(以字节为单位)的XML节点
out.println("this is a file with name: " + item.getName());
}
}
//关闭响应XML数据和流
out.close();
//对所有异常的基本处理
// // TODO:发生错误时有用的东西
} catch (FileUploadException fue) {
fue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}