页面
<%@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>
<form action="UplodeServlet" method="post" enctype="multipart/form-data">
<
<input type="file" id="file" name="file">
<input type="submit">
</form>
</html>
说明1:提交方式必须是post
说明2:enctype=“multipart/form-data” , 为什么要是用这个呢?百度一下就知道了。
说明3: web.xml就不贴了
第一个版本:纯servlet方式,不使用任何第三方包代码如下:
package TestServlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* servlet原始上传文件
* @author Administrator
*
*/
public class UplodeServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 判断是否有上传的文件,通过ContentType来判断,因为上传文件的时候,enctype="multipart/form-data"
// 并且提交的方式必须是post
String contentType = req.getContentType();
String method = req.getMethod();
if (!method.toLowerCase().equals("post")) {
System.out.println("提交方式不是post");
return;
}
if (!contentType.toLowerCase().startsWith("multipart/")) {
System.out.println("此请求不是上传请求");
return;
}
StringBuilder sb = new StringBuilder();
// 获取上传文件的二进制文件内容,req.getInputStream()里面的内容只能读取一次,直接写入临时文件方便重复使用
// 有人说在用ISO8859-1编码好一些,没测试过,目前只测试了文本类型
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
String line = null;
int count = 1;
String head = new String();
String fileInfo = new String();
String fileType = new String();
String tmpPath = "d:\\upload\\tmp";
new File(tmpPath).mkdirs();
// 构建临时文件
tmpPath = tmpPath + UUID.randomUUID() + ".tmp";
OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(tmpPath), "utf-8");
while ((line = reader.readLine()) != null) {
if (count == 1) {
head = line;
}
// 解析文件名Content-Disposition: form-data; name="file";
// filename="josn.txt"
if (count == 2) {
fileInfo = line;
}
// 解析Content-Type: text/plain
if (count == 3) {
fileType = line;
}
// count>=4的时候才能接收数据
if (count > 4) {
// 截取最后一段不必要数据
if (line.contains(head.toString())) {
System.err.println("包含字符");
} else {
// 边循环边写入文件
os.write(line);
os.flush();
}
}
count++;
}
// 解析出文件名称
String fileName = fileInfo.substring(fileInfo.lastIndexOf("filename="), fileInfo.length());
os.close();
// 显示数据
resp.setContentType("text/html;charset=UTF-8");
PrintWriter pw = resp.getWriter();
pw.println("文件名:" + fileName);
pw.println("文件类型:" + fileType);
}
}
代码注释的都很清楚了,就不解释了。 代码写的不好,请见谅。
第一版能满足普通上传,但是如果是多文件上传的情况,那么代码的复杂度和要考虑的问题就特别多,然后就出来了commons-fileupload和commons-io两个组件,原理应该和第一版一样,只是,多了很多细节化处理。
第二版,直接使用commons-fileupload和commons-io两个组件,代码如下:
package TestServlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UplodeServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTf-8");
//获取tomcat下的up目录的路径
String path = "d:\\upload\\up";
//临时文件目录
String tmpPath = "d:\\upload\\tmp";
//检查我们是否有文件上传请求
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
//1,声明DiskFileItemFactory工厂类,用于在指定磁盘上设置一个临时目录
DiskFileItemFactory disk = new DiskFileItemFactory(1024*10,new File(tmpPath));
//2,声明ServletFileUpload,接收上边的临时文件。也可以默认值
ServletFileUpload up = new ServletFileUpload(disk);
//3,解析request
try {
List<FileItem> list = up.parseRequest(req);
//如果就一个文件,
FileItem file = list.get(0);
//获取文件名:
String fileName = file.getName();
//获取文件的类型:
String fileType = file.getContentType();
//获取文件的字节码:
InputStream in = file.getInputStream();
//文件大小
int size = file.getInputStream().available();
//声明输出字节流
OutputStream out = new FileOutputStream(path+"/"+fileName);
//文件copy
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
out.flush();
out.close();
//删除上传生成的临时文件
file.delete();
//显示数据
resp.setContentType("text/html;charset=UTF-8");
PrintWriter pw = resp.getWriter();
pw.println("文件名:"+fileName);
pw.println("文件类型:"+fileType);
pw.println("<br/>文件大小(byte):"+size);
} catch (FileUploadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
第二版本明显比第一版本更加清晰,而且很多上传细节处理我们并不用关心,值需要关注从FileItem里取出来就行。现在大多说的上传下载组件,都是基于第二版进行升级。