自学java,选择从简单的javaweb入手了。
读了网上某位大神的细致文章,了解后自己写了这篇上传下载的,加上了自己一部分的理解注释。
算是入门篇吧。大致完成了任务,比较粗糙。
fileHanderServlet.java (文件上传处理)
1 package up.file.Servletfile; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.util.List; 9 import java.util.UUID; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.annotation.WebServlet; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 17 import org.apache.commons.fileupload.FileItem; 18 import org.apache.commons.fileupload.FileUploadBase; 19 import org.apache.commons.fileupload.FileUploadException; 20 import org.apache.commons.fileupload.ProgressListener; 21 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 22 import org.apache.commons.fileupload.servlet.ServletFileUpload; 23 24 /** 25 * Servlet implementation class fileHandleServlet 26 */ 27 @WebServlet("/fileHandleServlet") 28 public class fileHandleServlet extends HttpServlet { 29 private static final long serialVersionUID = 1L; 30 31 /** 32 * @see HttpServlet#HttpServlet() 33 */ 34 public fileHandleServlet() { 35 super(); 36 // TODO Auto-generated constructor stub 37 } 38 39 /** 40 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 41 */ 42 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 43 //获取上传目录 44 String filePath=this.getServletContext().getRealPath("/WEB-INF/upload"); 45 //设置临时上传目录 46 String tempPath=this.getServletContext().getRealPath("/WEB-INF/temp"); 47 //设置message消息 48 String message=""; 49 //System.out.println("filePath:="+filePath); 50 //将文件目录转为文件 51 File file=new File(filePath); 52 //将临时文件目录转为文件 53 File tempfile=new File(tempPath); 54 //System.out.println("file:="+file); 55 //isDirectory()文件夹是否为文件,exists()是否存在 56 if(!file.exists()&&!file.isDirectory()) 57 { 58 System.out.println("该文件不存在,重新创建!"); 59 file.mkdirs(); 60 } 61 //判断临时文件目录是否存在 62 if(!tempfile.exists()&&!tempfile.isDirectory()) 63 { 64 System.out.println("该临时文件不存在,重新创建!"); 65 tempfile.mkdirs(); 66 } 67 //创建DiskDiskFileItemFactory工厂 68 DiskFileItemFactory factory=new DiskFileItemFactory(); 69 //设置factory工厂的缓冲区大小 70 factory.setSizeThreshold(1024*1025*5);//1024字节*1024*5=5M 71 //设定临时上传文件目录 72 factory.setRepository(tempfile); 73 //创建文件上传解析器 74 ServletFileUpload upload=new ServletFileUpload(factory); 75 //设置字符 76 upload.setHeaderEncoding("UTF-8"); 77 //判断上传的是普通表单还是带文件上传的表单 78 //isMultipartContent() 带文件上传的返回为true,普通表单为false 79 //System.out.println(ServletFileUpload.isMultipartContent(request)); 80 //进度监听 81 upload.setProgressListener( 82 new ProgressListener(){ 83 public void update(long pBytesRead,long pContentLength,int arg2){ 84 System.out.println("文件大小为:"+pContentLength+",当前已处理:"+pBytesRead+",arg2:="+arg2); 85 } 86 }); 87 88 if(!ServletFileUpload.isMultipartContent(request)) 89 { 90 return; 91 } 92 //System.out.println("获取打印:="+upload.parseRequest(request)); 93 //将文件装入List数组类中 94 //设置单个文件上传最大值 1024*1024 95 upload.setFileSizeMax(1024*1024*10); 96 //设置上传文件总量大小 97 upload.setSizeMax(1024*1024*100); 98 try { 99 List<FileItem> filelist=upload.parseRequest(request); 100 //System.out.println("List:="+filelist); 101 //isFormFiled判断普通表单和FILE表单 102 for(FileItem item:filelist) 103 { 104 if(item.isFormField()) 105 { 106 /*System.out.println("getFiledName():="+item.getFieldName());*/ 107 String name=item.getFieldName();//获取jsp页面text上input名 108 String value=item.getString("UTF-8");//获取jsp页面text上的value值 109 System.out.println(name+"="+value); 110 }else 111 { 112 String filename=item.getName();//获取jsp传的文件名 113 int lenth=item.getFieldName().length(); 114 System.out.println("lenth:="+lenth); 115 //System.out.println("hash:filename="+filename); 116 filename=unqueFilename(filename); 117 //hash打乱存储目录 118 filename=hashfile(filename,filePath); 119 //System.out.println("filename:="+filename); 120 if(filename.trim().equals("")&&filename==null) 121 { 122 continue; 123 } 124 //创建输入流和输出流,将文件写入到缓存空间 125 //在对文件进行存入的时候,设置输入流,并利用输入流将文件存入缓存区后,使用文件输出流FileOutputStream输出到文件中 126 filename=filename.substring(filename.lastIndexOf("\\")+1); 127 //每一个item创建一个输入流 128 InputStream in=item.getInputStream(); 129 System.out.println("item.getInputStream:="+item.getInputStream()); 130 System.out.println("item:="+item); 131 //每一个item创建一个文件输出流 132 //System.out.println("完整连接:="+filePath+"\\"+filename); 133 FileOutputStream out=new FileOutputStream(filePath+"\\"+filename); 134 //创建缓存区1024*1024*5=5m 135 byte buffer[]=new byte[1024*1024*5]; 136 int len=0; 137 //将文件存入缓存区 138 //System.out.println("in.read值:="+in.read(buffer)); 139 while((len=in.read(buffer))>0) 140 { 141 out.write(buffer,0,len); // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流 142 } 143 in.close();//关闭输入流 144 out.close();//关闭输出流 145 item.delete();//删除临时的文件 146 message="文件上传成功!"; 147 } 148 } 149 } 150 catch(FileUploadBase.FileSizeLimitExceededException e){ 151 message="单个文件上传超出限制!"; 152 String filename=e.getFileName(); 153 //System.out.println("抛出file:="+e.getFileName()); 154 //System.out.println("抛出field:="+e.getFieldName()); 155 byte buffer[]=new byte[1024*1024*10]; 156 //checkFilewrite(filename,filePath,buffer); 157 e.printStackTrace(); 158 } 159 catch(FileUploadBase.SizeLimitExceededException e){ 160 message="上传总数超出限制!"; 161 e.printStackTrace(); 162 } 163 catch (FileUploadException e) { 164 // TODO Auto-generated catch block 165 message="文件上传失败"; 166 e.printStackTrace(); 167 } 168 request.setAttribute("message", message); 169 request.getRequestDispatcher("/message.jsp").forward(request, response); 170 } 171 172 //获取唯一文件名 173 public String unqueFilename(String filename){ 174 return UUID.randomUUID().toString()+"_"+filename; 175 } 176 //hash打乱存储目录 177 public String hashfile(String filename,String filePath){ 178 int hashcode=filename.hashCode(); 179 int dir1=hashcode&0xf; 180 int dir2=(hashcode&0xf0)>>4; 181 String dir=filePath+"\\"+dir1+"\\"+dir2+"\\"+filename; 182 //System.out.println("dir1:="+dir1+"dir2:="+dir2+"dir:="+dir); 183 return dir; 184 } 185 //文件写入缓存区间 186 public void checkFilewrite(String filename,String filePath,byte buffer[]){ 187 int len=0; 188 InputStream ip; 189 FileOutputStream op; 190 try { 191 ip=new FileInputStream(filePath+"\\"+filename); 192 op=new FileOutputStream(filePath+"\\"+filename); 193 while((len=ip.read(buffer))>0){ 194 op.write(buffer,0,len); 195 } 196 } catch (IOException e) { 197 // TODO Auto-generated catch block 198 e.printStackTrace(); 199 } 200 201 } 202 203 /** 204 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 205 */ 206 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 207 // TODO Auto-generated method stub 208 doGet(request, response); 209 } 210 211 }
fileListServlet.java (文件下载页面处理)
1 package up.file.Servletfile; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 /** 15 * Servlet implementation class fileListServlet 16 */ 17 @WebServlet("/fileListServlet") 18 public class fileListServlet extends HttpServlet { 19 private static final long serialVersionUID = 1L; 20 21 /** 22 * @see HttpServlet#HttpServlet() 23 */ 24 public fileListServlet() { 25 super(); 26 // TODO Auto-generated constructor stub 27 } 28 29 /** 30 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 31 */ 32 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33 // TODO Auto-generated method stub 34 //response.getWriter().append("Served at: ").append(request.getContextPath()); 35 //获取文件上传目录 36 String filePath=this.getServletContext().getRealPath("/WEB-INF/upload"); 37 //上传目录转为文件 38 File file=new File(filePath); 39 //通过Map接口实现存储下载文件 40 Map<String,String> filemap=new HashMap<String,String>(); 41 filelist(file,filemap); 42 43 request.setAttribute("filemap", filemap); 44 request.getRequestDispatcher("/listFile.jsp").forward(request, response); 45 46 } 47 48 public void filelist(File file,Map<String,String> map){ 49 //如果file不是文件,是目录,则遍历该目录下所有的文件 50 if(!file.isFile()){ 51 File files[]=file.listFiles(); 52 for(File item:files){ 53 filelist(item,map); 54 } 55 }else{ 56 //如果file是文件,则取出uuid后的真实文件名,存入map中 57 String realname=file.getName().substring(file.getName().indexOf("_")+1); 58 String filename=file.getName(); 59 System.out.println("realname:="+realname+"filename:="+filename); 60 map.put(filename, realname); 61 } 62 } 63 64 /** 65 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 66 */ 67 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 68 // TODO Auto-generated method stub 69 doGet(request, response); 70 } 71 72 }
downLoadServlet.java (文件下载处理)
1 package up.file.Servletfile; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.OutputStream; 8 import java.net.URLEncoder; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.annotation.WebServlet; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 /** 17 * Servlet implementation class DownLoadServlet 18 */ 19 @WebServlet("/DownLoadServlet") 20 public class DownLoadServlet extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public DownLoadServlet() { 27 super(); 28 // TODO Auto-generated constructor stub 29 } 30 31 /** 32 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 // TODO Auto-generated method stub 36 //response.getWriter().append("Served at: ").append(request.getContextPath()); 37 //获取上传文件名 38 String filename=request.getParameter("filename"); 39 String message=""; 40 //取出UUID后获取真实文件名 41 String realname=filename.substring(filename.lastIndexOf("_")+1); 42 //设置浏览器相应头 43 response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(realname,"UTF-8")); 44 //获取上传目录 45 String filePath=this.getServletContext().getRealPath("/WEB-INF/upload"); 46 //获取该文件 47 File file=new File(filePath+"\\"+filename); 48 //判断文件是否存在 49 if(!file.exists()){ 50 message="该文件已经被删除!"; 51 request.setAttribute("message", message); 52 request.getRequestDispatcher("/message.jsp").forward(request, response); 53 } 54 //设置文件输入流,利用文件输入流,将需要下载的文件输入到文件输入流中,利用输出流读取存入缓存区的文件,然后输出 55 FileInputStream fileip=new FileInputStream(filePath+"\\"+filename); 56 OutputStream out=response.getOutputStream(); 57 int len=0; 58 byte buffer[]=new byte[1024*1024]; 59 while((len=fileip.read(buffer))>0){ 60 out.write(buffer,0,len); 61 } 62 63 fileip.close(); 64 out.close(); 65 } 66 67 /** 68 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 69 */ 70 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 71 // TODO Auto-generated method stub 72 doGet(request, response); 73 } 74 75 }
JSP现实采用了C标签
具体源码如下,注释比较消息,这里就不多解释了,有不对或者注释解释错误的地方,求各位指正,小弟初学java才一周。
源码:http://share.weiyun.com/f09e8aeffdae8167384def96fda3cb17
时间: 2024-11-10 08:16:28