JavaWeb之文件上传
1.上传组件
①Apache的Commons FileUpload
②JavaZoom的UploadBean
③JspSmartUpload
2.下载Commons的FileUpload组件
地址:http://commons.apache.org/fileupload/
同时还要下载Commons的IO组件
地址:http://commons.apache.org/io/
3.使用实例
步骤一:创建文件上传的页面:fileUpload.jsp
注意表单的 enctype 属性,这个设置很重要,详情请见:http://www.cnblogs.com/yinger/archive/2011/09/11/2173689.html
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="<%=request.getContextPath() %>/servlet/FileUploadServlet" method="post" enctype="multipart/form-data" >
上传人名:<input type="text" name="name" /><br/>
上传文件:<input type="file" name="file" /><br/>
<input type="submit" name="submit" value="提交" />
</form>
</body>
</html>
步骤二:创建处理文件上传的servlet:fileUploadServlet
package com.yinger.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
private ServletContext sc;
private String savePath;
private static final long serialVersionUID = 151650843430214502L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);//通过工厂生成一个处理文件上传的servlet对象
try {
List items = servletFileUpload.parseRequest(request);//解析request
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if(item.isFormField()){//表单的参数字段
System.out.println("表单的参数名称:"+item.getFieldName()+",表单的参数值:"+item.getString("UTF-8"));
}else {
if(item.getName()!=null && !item.getName().equals("")){//一个上传的文件
System.out.println("文件的名称:"+item.getName());
System.out.println("文件的大小:"+item.getSize());
System.out.println("文件的类型:"+item.getContentType());
File tempFile = new File(item.getName());//getName得到的文件名称包含了它在客户端的路径
File file = new File(sc.getRealPath("/")+savePath,tempFile.getName());
item.write(file);//将上传的文件写入到file中
request.setAttribute("message", "上传文件成功!");
}else{
request.setAttribute("message", "没有选择上传文件!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "上传文件失败!");
}
request.getRequestDispatcher("/fileUploadResult.jsp").forward(request, response);//转向,输出结果
}
@Override
public void init(ServletConfig config) throws ServletException {
savePath = config.getInitParameter("savePath");
sc = config.getServletContext();
}
}
步骤三:修改web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web=http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.yinger.servlet.FileUploadServlet</servlet-class>
<init-param> <!-- Servlet的初始化参数,配置上传文件的保存路径,这里是当前应用的uplods目录下 -->
<param-name>savePath</param-name>
<param-value>uploads</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/servlet/FileUploadServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
同时在项目的根目录下创建文件夹 uploads (可以就在WebRoot中创建)
步骤四:创建显示上传结果的页面:fileUploadResult.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
</head>
<body>
<p>
${requestScope['message'] }<br/>
</p>
</body>
</html>
效果展示