今天复习了下commons-fileupload文件上传,写了个demo。需要的jar包为:commons-fileupload-1.2.1.jar、commons-io-1.4.jar。都可去apache下的commons下下载。
一、上传
1、index.jsp
view plaincopy to clipboardprint?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="/commons-fileupload/UploadServlet" method="post" enctype="multipart/form-data">
username:
<input type="text" name="username">
<br>
password:
<input type="password" name="password">
<br>
file1:
<input type="file" name="file1">
<br>
file2:
<input type="file" name="file2">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
2、UploadServlet.java
view plaincopy to clipboardprint?
package com.fileupload.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
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;
@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {
@SuppressWarnings({ "unchecked", "deprecation" })
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//设置文件存储路径
String path = request.getRealPath("/upload");
//实例化工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置在内存中存储文件的的大小为1M,如果超出1M,将写入磁盘
factory.setSizeThreshold(1024*1024);
//如果文件超出1M,将写入磁盘
factory.setRepository(new File(path));
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
try {
//将request解析成FileItem,每个FileItem对应页面的一个输入对象。
List<FileItem> list = servletFileUpload.parseRequest(request);
for(FileItem item :list){
if(item.isFormField()){//如果输入域是普通类型type=text(非file类型)
String name = item.getFieldName();
String value = item.getString("UTF-8");
request.setAttribute(name, value);
}else{//如果输入域是type=file类型
String name = item.getFieldName();
String value = item.getName();//将取到如下内容:eg:C:\Documents and Settings\liu\桌面\test.doc
int start = value.lastIndexOf("\\");
String fileName = value.substring(start+1);//解析成test.doc
request.setAttribute(name, fileName);
// //使用普通流写入文件
// OutputStream out = new FileOutputStream(new File(path+"/"+fileName));
// InputStream in = item.getInputStream();
// byte buffer[]= new byte[1024];
// int length = 0;
// while((length=in.read(buffer))>0){
// out.write(buffer,0,length);
// }
// out.flush();
// out.close();
// in.close();
//使用FileItem提供的方法,方便的输出
item.write(new File(path+"/"+fileName));
}
}
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("success.jsp").forward(request, response);
}
}
3、success.jsp
view plaincopy to clipboardprint?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'success.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
</head>
<body>
username:${username }<br>
password:${password }<br>
file1:${file1 }<br>
file2:${file2 }<br>
</body>
</html>
4、web.xml
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.fileupload.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
二:下载:
下载文件用一个Servlet完成:
view plaincopy to clipboardprint?
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
Long id=Long.valueOf(request.getParameter("id"));
FileInfo fileInfo=fileDAO.find(id);
response.setContentType("application/x-msdownload;");
//此行代码是防止中文乱码的关键!!
response.setHeader("Content-disposition","attachment; filename="+new String(fileInfo.getName().getBytes("gb2312"),"iso8859-1"));
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(fileInfo.getPath()));
BufferedOutputStream bos=new BufferedOutputStream(response.getOutputStream());
//新建一个2048字节的缓冲区
byte[] buff=new byte[2048];
int bytesRead;
while((bytesRead=bis.read(buff, 0, buff.length))!=-1)
{
bos.write(buff);
}
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}