SP Servlet 文件上传我们首先需要准备两个jar包
需要在你的classpath中引入最新的 commons-fileupload.x.x.jar 包文件。
下载地址为:http://commons.apache.org/fileupload/
需要在你的classpath中引入最新的 commons-io-x.x.jar 。
下载地址为:http://commons.apache.org/io/
创建项目
在创建项目最后一步记得选上 Generate web.xml deployment descriptor
创建 upload.jsp 文件
页面的表单应该设为post方式提交,并且设置 enctype="multipart/form-data"
${message}为显示上传操作结果通知。
<body>
<form action="uploadServlet" enctype="multipart/form-data" method="post">
文件上传支持以下格式:"txt","doc","docx","xls","xlsx","ppt","pdf","xml","html","jpg","png"<br/>
文件上传:<input type="file" name="file" size="80"/>
<input type="submit" value="提交"><br/>
</form>
<span>${message}</span>
</body>
创建 UploadServlet 类
判断上传类型,注意:文件上传名重复,会覆盖原有文件。
存放目录本例 存放于 "D://workshop//upload_data", 根据自己情况修改
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf-8");
String allowTypes = new String{"txt","doc","docx","xls","xlsx","ppt","pdf","xml","html","jpg","png"};
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// String path = request.getSession().getServletContext().getRealPath("/files");
String path = "D://workshop//upload_data";
System.out.println(path);
try {
List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()){
System.out.println("文本信息");
}else{
if (item.getName() != null && !item.getName().equals("")) {
String name = item.getName();
String type = name.substring(name.lastIndexOf('.')+1);
boolean flag = false;
for(String at:allowTypes){
if(at.equals(type)){
flag = true;
}
}
if(flag==false){
System.out.println("文件格式不支持");
request.setAttribute("message", "文件格式不支持");
}else{
int start = name.lastIndexOf("\\");
String filename = name.substring(start+1);
File file = new File(path+"/"+filename);
item.write(file);
request.setAttribute("message", "文件上传成功");
}
}else{
System.out.println("请选择待上传文件");
request.setAttribute("message", "请选择待上传文件");
}
}
}
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "文件上传失败");
}
request.getRequestDispatcher("upload.jsp").forward(request, response);
}
配置 web.xml
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>cn.crabshell.controller.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
测试
启动服务器后,浏览器中输入:http://localhost:8080/uploadFileDemo/upload.jsp
选择文件
提交
查看目标文件夹
本例下载 uploadFileDemo.zip