JavaServlet的文件上传和下载实现方法
先分析一下上传文件的流程
1-先通过前段页面中的选择文件选择要上传的图片
index.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8" contentType="text/html;charset=UTF-8"%>MyJSP'index.jsp'startingpage 下载
2-点击提交按钮,通过ajax的文件上传访问服务器端
common.js
varpath=(function(){ //获取当前网址 varcurWwwPath=window.document.location.href; //获取主机地址之后的目录 varpathName=window.document.location.pathname; varpos=curWwwPath.indexOf(pathName); //获取主机地址 varlocalhostPath=curWwwPath.substring(0,pos); //获取带"/"的项目名 varprojectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); return{ curWwwPath:curWwwPath, pathName:pathName, localhostPath:localhostPath, projectName:projectName, //部署路径 deployPath:localhostPath+projectName }; })();
//文件下载 $("a[id=downLoad]").click(function(){ window.location.href=path.deployPath+"/fileDown"; }); //文件上传 $("input[id=upload]").click(function(){ $.ajaxFileUpload({ url:path.deployPath+"/fileUp",//处理页面的绝对路径 fileElementId:"inputImage",//file空间的id属性 dataType:"json", success:function(data){ alert("上传成功"); } }); });
3-服务器端响应保存或者下载
保存上传文件的FileUpload.java
importjava.io.File; importjava.io.IOException; importjava.io.PrintWriter; importjava.util.ArrayList; importjava.util.List; importjava.util.UUID; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importnet.sf.json.JSONArray; importorg.apache.commons.fileupload.FileItem; importorg.apache.commons.fileupload.FileUploadException; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; importcom.stu.util.HttpUtil; /** *文件名称:com.stu.fileupload.FileUpload.java
*初始作者:Administrator
*创建日期:2018-1-31
*功能说明:文件上传
*=================================================
*修改记录:
*修改作者日期修改内容
*================================================
*Copyright(c)2010-2011.Allrightsreserved.
*/ publicclassFileUploadextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; @Override protectedvoidservice(HttpServletRequestreq,HttpServletResponseres) throwsServletException,IOException{ //获取到当前服务器所在的路径 StringserverPath=req.getSession().getServletContext().getRealPath("/"); //设置保存上传文件的路径 StringsaveDirPath=serverPath+"img"; FilesaveDirPathFileObj=newFile(saveDirPath); //如果当用来存放文件的目录不存在时,要创建该目录 if(!saveDirPathFileObj.exists()){ saveDirPathFileObj.mkdirs(); } //创建一个解析器工厂 DiskFileItemFactoryfactory=newDiskFileItemFactory(); //设置工厂的缓存区大小 factory.setSizeThreshold(5*1024); //文件上传的解析器(文件上传对象) ServletFileUploadupload=newServletFileUpload(factory); //设置上传文件的最大值 upload.setSizeMax(3*1024*1024); //设置编码格式 upload.setHeaderEncoding("UTF-8"); try{ //上传以后的文件名 ListuploadFileNames=newArrayList (); List fileItems=upload.parseRequest(req); System.out.println(fileItems); for(FileItemfile:fileItems){ //新的文件名 StringsaveFileName=UUID.randomUUID().toString().replace("-",""); //文件的后缀 StringoldFileName=newString(file.getName().getBytes(), "UTF-8"); System.out.println("oldFileName"+oldFileName); StringfileType=oldFileName.substring(oldFileName.lastIndexOf(".")); //新的文件路径 StringsaveFilePath=saveDirPath+File.separator +saveFileName+fileType; uploadFileNames.add(saveFileName+fileType); //保存上传的文件 file.write(newFile(saveFilePath)); } System.out.println(uploadFileNames); HttpUtil.setAttribute(req,"urls",uploadFileNames); res.setContentType("application/json;charset=utf-8"); PrintWriterpw=res.getWriter(); pw.print(JSONArray.fromObject(uploadFileNames)); }catch(FileUploadExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); } } }
下载文件的FileDownload.java
importjava.io.File; importjava.io.IOException; importjava.io.PrintWriter; importjava.util.ArrayList; importjava.util.List; importjava.util.UUID; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importnet.sf.json.JSONArray; importorg.apache.commons.fileupload.FileItem; importorg.apache.commons.fileupload.FileUploadException; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; importcom.stu.util.HttpUtil; /** *文件名称:com.stu.fileupload.FileUpload.java
*初始作者:Administrator
*创建日期:2018-1-31
*功能说明:文件上传
*=================================================
*修改记录:
*修改作者日期修改内容
*================================================
*Copyright(c)2010-2011.Allrightsreserved.
*/ publicclassFileUploadextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; @Override protectedvoidservice(HttpServletRequestreq,HttpServletResponseres) throwsServletException,IOException{ //获取到当前服务器所在的路径 StringserverPath=req.getSession().getServletContext().getRealPath("/"); //设置保存上传文件的路径 StringsaveDirPath=serverPath+"img"; FilesaveDirPathFileObj=newFile(saveDirPath); //如果当用来存放文件的目录不存在时,要创建该目录 if(!saveDirPathFileObj.exists()){ saveDirPathFileObj.mkdirs(); } //创建一个解析器工厂 DiskFileItemFactoryfactory=newDiskFileItemFactory(); //设置工厂的缓存区大小 factory.setSizeThreshold(5*1024); //文件上传的解析器(文件上传对象) ServletFileUploadupload=newServletFileUpload(factory); //设置上传文件的最大值 upload.setSizeMax(3*1024*1024); //设置编码格式 upload.setHeaderEncoding("UTF-8"); try{ //上传以后的文件名 ListuploadFileNames=newArrayList (); List fileItems=upload.parseRequest(req); System.out.println(fileItems); for(FileItemfile:fileItems){ //新的文件名 StringsaveFileName=UUID.randomUUID().toString().replace("-",""); //文件的后缀 StringoldFileName=newString(file.getName().getBytes(), "UTF-8"); System.out.println("oldFileName"+oldFileName); StringfileType=oldFileName.substring(oldFileName.lastIndexOf(".")); //新的文件路径 StringsaveFilePath=saveDirPath+File.separator +saveFileName+fileType; uploadFileNames.add(saveFileName+fileType); //保存上传的文件 file.write(newFile(saveFilePath)); } System.out.println(uploadFileNames); HttpUtil.setAttribute(req,"urls",uploadFileNames); res.setContentType("application/json;charset=utf-8"); PrintWriterpw=res.getWriter(); pw.print(JSONArray.fromObject(uploadFileNames)); }catch(FileUploadExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); } } }
这里面用到了一个HttpUtil类,代码如下:
importjavax.servlet.FilterConfig; importjavax.servlet.ServletConfig; importjavax.servlet.ServletContext; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpSession; /** *文件名称_com.niit.model2.util.Httputil.java *初始作逯ܿAdministrator *创建日期_2018-1-23 *功能说明_这里用一句话描述这个类的作用--此句话需删除
*=================================================
*修改记录_br/> *修改作迠日期修改内容
*================================================
*Copyright(c)2010-2011.Allrightsreserved.
*/ publicclassHttpUtil{ privateHttpUtil(){ } /** *方法描述:[用于向不同的作用域存放属性] *初始作迺Administrator
*创建日期:2018-1-23-上午11:24:45
*弿Nj版本:2.0.0
*=================================================
*修改记录_br/> *修改作迠日期修改内容
*================================================
*void */ publicstaticvoidsetAttribute(ObjectscopeObj,Stringname,Objectvalue){ if(scopeObjinstanceofHttpServletRequest){ ((HttpServletRequest)scopeObj).setAttribute(name,value); } if(scopeObjinstanceofHttpSession){ ((HttpSession)scopeObj).setAttribute(name,value); } if(scopeObjinstanceofServletContext){ ((ServletContext)scopeObj).setAttribute(name,value); } } /** *方法描述:[获取作用域中指定名称的属性思 *初始作迺Administrator
*创建日期:2018-1-23-上午11:29:17
*弿Nj版本:2.0.0
*=================================================
*修改记录_br/> *修改作迠日期修改内容
*================================================
* *@paramscopeObj *@paramname *@return *Object */ publicstaticObjectgetAttribute(ObjectscopeObj,Stringname){ if(scopeObjinstanceofHttpServletRequest){ return((HttpServletRequest)scopeObj).getAttribute(name); } if(scopeObjinstanceofHttpSession){ return((HttpSession)scopeObj).getAttribute(name); } if(scopeObjinstanceofServletContext){ return((ServletContext)scopeObj).getAttribute(name); } returnnull; } /** *方法描述:[获取上下文对象的方法] *初始作迺Administrator
*创建日期:2018-1-23-上午11:31:26
*弿Nj版本:2.0.0
*=================================================
*修改记录_br/> *修改作迠日期修改内容
*================================================
* *@return *ServletContext */ publicstaticServletContextgetServletContext(ObjectsourceObj){ if(sourceObjinstanceofHttpServletRequest){ return((HttpServletRequest)sourceObj).getSession().getServletContext(); } if(sourceObjinstanceofServletConfig){ return((ServletConfig)sourceObj).getServletContext(); } if(sourceObjinstanceofFilterConfig){ return((FilterConfig)sourceObj).getServletContext(); } returnnull; } /** *方法描述:[获取项目的实际路径] *初始作迺Administrator
*创建日期:2018-1-23-上午11:45:47
*弿Nj版本:2.0.0
*=================================================
*修改记录_br/> *修改作迠日期修改内容
*================================================
* *@paramreq *@return *String */ publicstaticStringgetContextPath(HttpServletRequestreq){ returnreq.getContextPath(); } }
当然,代码编辑好了也不要忘了在WebRoot/WEB-INF/web.xml中添加新建的Servlet,就是刚刚的两个Java文件啦
index.jsp fileUpload com.stu.fileupload.FileUpload fileUpload /fileUp fileDownload com.stu.fileupload.FileDownload fileDownload /fileDown
这样的话就可以运行啦。
TIP:不要忘记相关的jar包和js包哦
在WebRoot/WEB-INF/lib下,有commons-fileupload.jar和commons-io.jar,另外json-lib-x.x.x-jdkxx.jar包是用来把上传的返回数据修改为JSON格式的
在WebRoot/js下,导入jquery.js,common.js,ajaxfileupload.js
以上这篇JavaServlet的文件上传和下载实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。