//文件上传
public class UpServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter pout=response.getWriter();
try {
// 得到存放上传文件的真实路径
String storePath=getServletContext().getRealPath("WEB-INF/files");
// 设置环境
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setRepository(new File(getServletContext().getRealPath("/temp")));
// 判断一下form是否是enctype=multipart/form-data类型的
boolean isMutipart=ServletFileUpload.isMultipartContent(request);
if(!isMutipart){
System.out.println("菜鸟");
return;
}
// ServletFileUpload核心类
ServletFileUpload upload=new ServletFileUpload(factory);
// upload.setProgressListener(new ProgressListener() {
// //pBytesRead:当前以读取到的字节数
// //pContentLength:文件的长度
// //pItems:第几项
// public void update(long pBytesRead, long pContentLength,
// int pItems) {
// System.out.println("已读取:"+pBytesRead+",文件大小:"+pContentLength+",第几项:"+pItems);
// }
//
// });
// upload.setFileSizeMax(4 * 1024 * 1024);// 设置单个上传文件的大小
// upload.setSizeMax(6 * 1024 * 1024);// 设置总文件大小
// 解析
List<FileItem> items=upload.parseRequest(request);
for(FileItem item:items){
if(item.isFormField()){
String fieldName=item.getFieldName();
String fieldValue=item.getString("utf-8");
System.out.println(fieldName + "=" + fieldValue);
}else{
// 得到MIME类型
String mimeType=item.getContentType();
// 只允许上传图片
if(mimeType.startsWith("image")){
// 上传字段
InputStream in=item.getInputStream();
// 上传的文件名
String fileName=item.getName();
//如果文件不填跳过
if(fileName==null&&"".equals(fileName.trim())){
continue;
}
fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
fileName=UUID.randomUUID()+"_"+fileName;
System.out.println(request.getRemoteAddr()+"=============="+fileName);
// 构建输出流
// 打散存储目录
String newStorePath=makeStorePath(storePath,fileName);
// /WEB-INF/files和文件名,创建一个新的存储路径
// /WEB-INF/files/1/12
String storeFile=newStorePath+"\\"+fileName;
OutputStream out=new FileOutputStream(storeFile);
//设置缓存
byte b[]=new byte[1024];
int len=-1;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
in.close();
item.delete();//删除临时文件
}
}
}
} catch (FileUploadException e) {
throw new RuntimeException("服务器忙!");
}
request.getRequestDispatcher("/servlet/ShowAllFilesServlet").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
private String makeStorePath(String storePath, String fileName) {
// 根据 /WEB-INF/files和文件名,创建一个新的存储路径 /WEB-INF/files/1/12
int hashCode=fileName.hashCode();
int dir1=hashCode&0xf;
int dir2=(hashCode&0xf0)>>4;
String path=storePath+"\\"+dir1+"\\"+dir2;
File file=new File(path);
if(!file.exists())
file.mkdirs();
return path;
}
}
//文件的下载
public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
OutputStream out=response.getOutputStream();
String filename=request.getParameter("filename");
filename=new String(filename.getBytes("ISO-8859-1"),"utf-8");
//截取老文件名
String oldFileName=filename.split("_")[1];
//得到存储路径
String storePath=getServletContext().getRealPath("/WEB-INF/files");
//得到文件的全部路径
String filePath=makeStorePath(storePath,filename)+"\\"+filename;
//判断文件是否存在
File file=new File(filePath);
if(!file.exists()){
out.write("对比起!你要下载的文件可能已经不存在了".getBytes("UTF-8"));
return;
}
InputStream in=new FileInputStream(file);
//通知客户端以下载的方式打开
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldFileName, "UTF-8"));
byte[] b = new byte[1024];
int len = -1;
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.write("下载成功".getBytes("UTF-8"));
}
private String makeStorePath(String storePath, String filename) {
int hashCode = filename.hashCode();
int dir1 = hashCode & 0xf;// 0000~1111:整数0~15共16个
int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整数0~15共16个
String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12
File file = new File(path);
if (!file.exists())
file.mkdirs();
return path;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
//下载页面
<body>
<h1>本站有以下好图片</h1>
<c:forEach items="${map}" var="me">
<c:url value="/servlet/DownServlet" var="url">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value } <a href="${url}">下载</a><br/>
</c:forEach>
</body>
</html>
//显示文件页面
public class ShowAllFilesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String,String> map=new HashMap<String,String>();//key:UUID文件名;value:老文件名
//得到存储文件的根目录
String storePath=getServletContext().getRealPath("/WEB-INF/files");
//递归遍历其中文件
File file=new File(storePath);
treeWalk(file,map);
//交给JSP去显示:如何封装数据.用Map封装。key:UUID文件名;value:老文件名
request.setAttribute("map",map);
request.getRequestDispatcher("/Down.jsp").forward(request, response);
}
private void treeWalk(File file, Map<String, String> map) {
//遍历/WEB-INF/files所有文件,把文件名放到map中
if(file.isFile()){
//是文件
String uuidName=file.getName();
String oldName=uuidName.substring(uuidName.indexOf("_")+1);
map.put(uuidName, oldName);
}else{
//是一个目录
File[] fs=file.listFiles();
for(File f:fs){
treeWalk(f,map);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}