package cn.itcast.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 java.util.Random;
import java.util.UUID;
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 Servlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 获得表单参数 name=zhangsan&password=123
// 1. 创建解析工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// factory.setSizeThreshold(12);默认 10 k 缓存大小
// factory.setRepository(new File("d:\\temp2"));// 指定临时文件的存放目录
// 2. 创建用于解析request的FileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
// 3. 判断一下是否是文件上传表单
if(!upload.isMultipartContent(request)) {
request.setAttribute("message", "不是文件上传表单");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
// 4. 解析
List<FileItem> fileitems = null;
try {
fileitems = upload.parseRequest(request);
} catch (FileUploadException e) {
throw new RuntimeException(e);
}
// 5. 遍历
for(FileItem item : fileitems) {
// 判断是否为普通字段
if(item.isFormField()) {
// 获得字段的name和value
String name = item.getFieldName();
String value = item.getString("utf-8");
System.out.println(name + "=" + value);
} else {
// 上传字段
// 获得字段名
String name = item.getFieldName();
// 获得文件名
String filename = item.getName();
//System.out.println("before: " + filename);
filename = filename.substring(filename.lastIndexOf("\\")+1);
//System.out.println("after: " + filename);
System.out.println("filename=" + filename);
// 将文件名加上唯一的标识 保证文件名不重复
filename = UUID.randomUUID().toString() + "_" + filename; // a_b_c.jpg
System.out.println("filename=" + filename);
// 约定一个文件的存放目录 获得目录绝对路径
String dirPath = getServletContext().getRealPath("/WEB-INF/upload");
// 分目录 将文件打散
// 按照时间存放 年 月 日
/*
产生随机数 作为目录 弊端 将来无法查找
Random r = new Random();
int num = r.nextInt(16);
dirPath = dirPath + "\\" + num;
num = r.nextInt(16);
dirPath = dirPath + "\\" + num;
*/
// 文件夹最好按照文件名来计算
int hashCode = filename.hashCode();// 010100111110110101010010101
int num = hashCode&0x0000000f;
dirPath = dirPath + "\\" + num;
// 二级目录 再拿高的四位 取值 0~15 相当于获得了随机数 只不过是计算出来的
num = (hashCode>>4)&0x0000000f;
dirPath = dirPath + "\\" + num;
// 创建必要的文件夹
File dir = new File(dirPath);
dir.mkdirs();
// 创建文件对象
File file = new File(dir, filename);
// 创建文件
file.createNewFile();
// 获得流
InputStream in = item.getInputStream();
OutputStream out = new FileOutputStream(file);
// 流的对拷
int len;
byte[] buffer = new byte[1024];
while((len=in.read(buffer))>0)
out.write(buffer, 0, len);
in.close();
out.close();
// 删除临时文件 在这之前需要关闭输入输出流
item.delete();
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}