文件上传
依赖的jar包:commons-fileupload-1.2.2.jar
commons-io-1.4.jar
form3.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'form2.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">
-->
</head>
<body>
<h1>上传3</h1>
<h3>${msg }</h3>
<form action="<c:url value='/Upload3Servlet'/>" method="post" enctype="multipart/form-data">
用户名;<input type="text" name="username"/><br/>
照 片:<input type="file" name="zhaoPian"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
java代码:
package cn.itcast.servlet;
import java.io.File;
import java.io.IOException;
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.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import cn.itcast.commons.CommonUtils;
public class Upload3Servlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
/*
* 上传三步
*/
// 工厂
DiskFileItemFactory factory = new DiskFileItemFactory(20*1024, new File("F:/f/temp"));
// 解析器
ServletFileUpload sfu = new ServletFileUpload(factory);
// sfu.setFileSizeMax(100 * 1024);//限制单个文件大小为100K
// sfu.setSizeMax(1024 * 1024);//限制整个表单大小为1M
// 解析,得到List
try {
List<FileItem> list = sfu.parseRequest(request);
FileItem fi = list.get(1);
//////////////////////////////////////////////////////
/*
* 1. 得到文件保存的路径
*/
String root = this.getServletContext().getRealPath("/WEB-INF/files/");
/*
* 2. 生成二层目录
* 1). 得到文件名称
* 2). 得到hashCode
* 3). 转发成16进制
* 4). 获取前二个字符用来生成目录
*/
String filename = fi.getName();//获取上传的文件名称
/*
* 处理文件名的绝对路径问题
*/
int index = filename.lastIndexOf("\\");
if(index != -1) {
filename = filename.substring(index+1);
}
/*
* 给文件名称添加uuid前缀,处理文件同名问题
*/
String savename = UUID + "_" + filename;
/*
* 1. 得到hashCode
*/
int hCode = filename.hashCode();
String hex = Integer.toHexString(hCode);
/*
* 2. 获取hex的前两个字母,与root连接在一起,生成一个完整的路径
*/
File dirFile = new File(root, hex.charAt(0) + "/" + hex.charAt(1));
/*
* 3. 创建目录链
*/
dirFile.mkdirs();
/*
* 4. 创建目录文件
*/
File destFile = new File(dirFile, savename);
/*
* 5. 保存
*/
fi.write(destFile);
///////////////////////////////////////////////////////
} catch (FileUploadException e) {
if(e instanceof FileUploadBase.FileSizeLimitExceededException) {
request.setAttribute("msg", "您上传的文件超出了100KB!");
request.getRequestDispatcher("/form3.jsp").forward(request, response);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}