通过JQuery中的AJAX函数来实现文档的上传,压缩,下载

    技术2022-05-19  22

    1.   文档上传的一个简单界面 docUpload.jsp:

      <%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'docUpload.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" mce_href="styles.css"> --> <mce:script type="text/javascript" src="resources/jquery.js" mce_src="resources/jquery.js"></mce:script> <mce:script type="text/javascript" src="resources/upload/fileUploadUtil.js" mce_src="resources/upload/fileUploadUtil.js"></mce:script> <mce:script type="text/javascript" src="resources/ajaxfileupload.js" mce_src="resources/ajaxfileupload.js"></mce:script> </head> <mce:script type="text/javascript"><!-- //默认设置上传文件的大小100M var uploadFileSize = "100000000"; $(document).ready(function(){ $("#test").click(function(){ uploadFile(); }); }); // --></mce:script> <body> <form action="#"> <table id="upload" border="1"> <tr> <td width="20%">序号</td> <td width="30%">名字</td> <td width="50%">路径</td> <td width="20%">状态</td> </tr> <tr> <td>1</td> <td>111</td> <td><input type="file" name="newfile" οnchange="checkFile(this);"></input></td> <td><p id="flag1">正常</p></td> </tr> </table> <input type="submit" value="确定" id="test"></input> </form> </body> </html>

     

     

    2.  fileUploadUtil.js 为上传下载文档都需要引入的JS

       /** * 定义全局变量 */ var uploadFileSize = ""; // 定义文档内容的大小 var checkFileFlag = false; //文件是否已经检查的标志 var fileCount = -1; var paramterUrl = ""; //定义传递到后台的参数 function uploadFile() { //对上传框内的内容进行判断 if(checkFileFlag == false) { checkFileFlag = true; var flag = checkFilePath(); if(flag) { alert("/u6587/u4ef6/u5730/u5740/u4e0d/u80fd/u4e3a/u7a7a!"); checkFileFlag = false; return; } } fileCount++; var fileId = ""; var filePath = ""; //这边是每次都对对应的需要上传的文档进行过滤 $(":file[id*='uploadFileName']").each(function(i){ if(i == fileCount) { fileId = $(this).attr("id"); filePath = $(this).val(); } }); if(filePath == null || filePath == "") { return; } else { $("p[id*='showName']").each(function(i){ if(i == fileCount) { $(this).text("/u6587/u4ef6/u4e0a/u4f20/u4e2d/u3002/u3002/u3002/u3002/u3002"); $("#test").attr("disabled","disabled"); //后面执行上传文件的动作,调用后台的Servlet doUploadFile(filePath,fileId); } }); } } /** * 执行上传文件的动作 */ function doUploadFile(filePath,fileId) { //获得上传文件的文件名 var paths = filePath.split("//"); var fileName = paths[paths.length - 1]; //定义传递到后台的参数 //paramterUrl = "name=lin&age=20"; var url = "/AJAX/servlet/FileUploadServlet?" + "name=linwei1111"; url = encodeURI(encodeURI(url)); //下面开始调用Servlet传递文件流到后台,下面是在ajaxfileupload.js文件中的,,就已经有enctype设置了。 //var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); $.ajaxFileUpload({ type:"POST", secureuri:false, //**文件上传空间的id属性,这边需要写入对应的上传文件的fileId fileElementId:fileId, dataType:"json", url: url, //data:{name:'linwei',age:'20'}, success:function(data){ if(data.status == "success") { $("p[id*='showName']").each(function(i){ if(i == fileCount) { $(this).text("/u4e0a/u4f20/u6210/u529f"); } }); } else { $("p[id*='showName']").each(function(i){ if(i == fileCount) { $(this).text("/u4e0a/u4f20/u5931/u8d25"); } }); } gotoNextUpload(); }, error:function(xhr,status,err) { alert("/u51fa/u9519/u4e86/u3002"); gotoNextUpload(); } }); } /** * 跳转到下一个页面,判断是否继续上传文档 */ function gotoNextUpload() { //获取上传文档的数量 var size = $(":file[id*='uploadFileName']").size(); if(fileCount<size-1) { uploadFile(); } else { $("#test").removeAttr("disabled"); } } /** * 检查文档路径是否为空 */ function checkFilePath() { var flag = false; $("input[name*='a']").each(function(i){ if($(this).val() == null || $(this).val() == "") { flag = true; return flag; } }); return flag; } /** * 文档上传之前,对上传的文档内容进行检查。(检查内容包括:文档后缀,文档大小等) */ function checkFile(obj) { //根据文档路径是否存在进行判断 if(obj.value.length>0) { //定义可以上传的文档类型 var af = "jpg,gif,png,zip,rar,txt,doc,htm,pdf,xls"; if (eval("with(obj.value)if(!/" + af.split(",").join("|") + "/ig.test(substring(lastIndexOf('.')+1,length)))1;")) { alert("/u5141/u8bb8/u4e0a/u4f20/u7684/u6587/u6863/u7c7b/u578b/u4e3a:/n" + af); //清楚文件上传框中的内容 obj.outerHTML = obj.outerHTML; } else { checkFileSize(obj); } } } /** * 检查文档内容的大小 */ function checkFileSize(obj) { if (!getFileSize(obj.value)) { obj.outerHTML = obj.outerHTML; alert("/u4e0a/u4f20/u6587/u4ef6/u5927/u5c0f/u8bf7/u52ff/u5927/u4e8e"+parseInt(Number(uploadFileSize)/(1000*1000))+"M"); } } /** * 取得上传文档的大小 */ function getFileSize(filePath) { var fileSize = "-1"; //通过Img对象装载,这个可以是可以,但是浏览器有严格限制,现在最主流的浏览器都是ie内核的, //ie7和ie8的在装载Img对象是用dynsrc装载不了,只有ie6可以,这可能跟内核有关系。 var image = new Image(); image.dynsrc = filePath; fileSize = image.fileSize; //另外一种方式获取文件大小的 //var fso,f; //fso=new ActiveXObject("Scripting.FileSystemObject"); //f=fso.GetFile(filePath); //var fileSize = f.size ; if(Number(fileSize)<Number(uploadFileSize)) { return true; } else { return false; } } //============================================================= /** * 页面载入后先执行的动作 */ $(document).ready(function(){ //对页面的文件进行ID的编排 $(":file").each(function(i){ var thisFileId = i + "uploadFileName"; //alert("a is " + thisFileId); $(this).attr("id",thisFileId); }); //对页面的显示内容进行ID的编排 $("p[id*='flag']").each(function(i){ var thisShowId = i + "showName"; //alert("b is " + thisShowId); $(this).attr("id",thisShowId); }); }); //============================================================= //页面调用文档函数 function doFileDown(id) { var url = "http://localhost:8080/AJAX/servlet/fileDownload?id=" + id; $("#" + id).attr("href",url); $("#" + id).click(function(){ alert($(this).attr("href")); }); }

     

     

     3.   FileUploadServlet.java 是上传的Servlet

     

       package upload; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadException; import service.JsonUtil; public class FileUploadServlet extends HttpServlet { Map map = new HashMap(); /** * Constructor of the object. */ public FileUploadServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("in doGet."); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println("in doGet method, using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println("in doPost."); // response.setContentType("text/html; charset=UTF-8"); // PrintWriter out = response.getWriter(); // String test = request.getParameter("name"); // System.out.println("test is " + test); // // String test1 = request.getParameter("age"); // System.out.println("test1 is " + test1); FileOperation fo = new FileOperation(); try { DocumentVO documentVO = fo.doWriteFile(request); //这边把序列号记录到记录文件中 fo.logSequenceNumber(documentVO); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); //这边取消记录文件中的序列号 try { fo.getLogFile(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); //这边取消记录文件中的序列号 try { fo.getLogFile(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // 向客户端添加返回的标志 String status = "success"; map.put("status", status); this.doCallbackMethod(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException * if an error occurs */ public void init() throws ServletException { // Put your code here } /** * 通过返回字段的设置,向客户端返回相应的信息,客户端通过回调方法获得信息后处理 * * @param request * @param response * @throws IOException */ private void doCallbackMethod(HttpServletRequest request, HttpServletResponse response) { PrintWriter writer = null; try { writer = response.getWriter(); // FormatForJSON f = new FormatForJSON(); // String json = f.object2json(map); JsonUtil json = JsonUtil.getInstanceFactory(); json.fromObject(map); System.out.println("json is " + json.getResult()); writer.print(json.getResult()); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } }

     

     

    4.  FileOperation.java 是文档的操作类

      

       package upload; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem; import doc.util.ZipUtil; /** * 文档操作类 * @author linwei * */ public class FileOperation { /** * 文档的写入方法 * @param request * @throws Exception */ public DocumentVO doWriteFile(HttpServletRequest request) throws Exception { //DiskFileUpload是commom-fileupload.jar包中的类 DiskFileUpload diskFileUpload = new DiskFileUpload(); //设置上传文件的大小,默认大小为100M diskFileUpload.setSizeMax(new Long(102400000)); //设置缓冲大小 diskFileUpload.setSizeThreshold(4096); //设置编码方式 diskFileUpload.setHeaderEncoding("GBK"); diskFileUpload.setHeaderEncoding("gb2312"); //解析请求,返回一个集合 List fileItem = diskFileUpload.parseRequest(request); if(fileItem.size() == 0) { System.out.println("数量为0."); } //这边是分别获取到每个的上传文件 Iterator it = fileItem.iterator(); //这边是循环每个文件,获取到每个文件下的属性,即FileItem对象 List list = null; Map map = null; DocumentVO documentVO = null; File file = null; while(it.hasNext()) { FileItem fi = (FileItem)it.next(); //这边获取文件流 InputStream in = fi.getInputStream(); if(in == null) { System.out.println("流是空的。"); } //这边开始处理文件 //如果是普通表单对象,则返回true,如果是文件表单字段,则返回false if(!fi.isFormField()) { list = new ArrayList(); map = new HashMap(); //返回的文件名包括客户机路径 String filePath = fi.getName(); String fileName = this.getFileName(filePath); String fileType = fileName.substring(fileName.lastIndexOf(".") + 1); fileName = fileName.substring(0,fileName.lastIndexOf(".")); documentVO = new DocumentVO(); documentVO.setFileName(fileName); documentVO.setFileType(fileType); documentVO = this.getSequenceNumber(documentVO); System.out.println("fileName is " + fileName); list.add(in); //for test // file = new File("D://Workspace//DocumentUpload//","linwei.txt"); // fi.write(file); //for test } } //开始调用上传文档方法 return this.upload(documentVO, list); } /** * 上传文档的操作类 * @param documentVO * @param list * @throws Exception */ private DocumentVO upload(DocumentVO documentVO,List list) throws Exception { if(documentVO == null || "".equals(documentVO)) { throw new Exception("documentVO 不能为空!"); } if(list == null || list.size() == 0) { throw new Exception("没有文件流。"); } InputStream in = (InputStream)list.get(0); return this.transferDocument(documentVO, in); } /** * 传输物理文件 * @param documentVO * @param in * @return */ private DocumentVO transferDocument(DocumentVO documentVO,Object bytesStream) { //这边先写死了一个路径,正确的应该是写在配置文件中的 String path = "D://Workspace//DocumentUpload//"; //********************************************** //这边传递的文件不能是路径,必须是已经拼装好的文件具体地址了 String fileAbsolutePath = path + documentVO.getSequenceNumber(); if(bytesStream instanceof InputStream) { //开始进行压缩 ZipUtil zipUtil = new ZipUtil(); Map map = new HashMap(); //这边传递的压缩文件的名字最好是文件的全名 map.put(documentVO.getFileName()+"."+documentVO.getFileType(), (InputStream)bytesStream); try { zipUtil.zip(fileAbsolutePath, map); System.out.println("OK"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); //如果出错了的话,就用常规的文件保存方式 this.write((InputStream)bytesStream, fileAbsolutePath,documentVO); } } else { this.write((OutputStream)bytesStream, fileAbsolutePath,documentVO); } //这边把序列号作为名字参数传递出去 return documentVO; } /** * 取得存储时候的文件名,最后也是根据这个名字去数据库中查询的 * @param fileName * @return */ private DocumentVO getSequenceNumber(DocumentVO documentVO) { //这边文件名字(fileName)传递进来以便后面可以使用 Calendar c = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); documentVO.setSequenceNumber(dateFormat.format(c.getTime())); return documentVO; } /** * 从路径中取得文件名 * @param fileName * @return */ private String getFileName(String filePath) { int pos = filePath.lastIndexOf(File.separator); // System.out.println("File.separator is " + File.separator); if(pos > 0) { //position为该字符串最右边出现的位置,substring(number)获取到该位置之后的字符串 return filePath.substring(pos + 1); } else { return filePath; } } /** * 把输入流对象持久化 * @param in */ public void write(InputStream in,String absolutePath,DocumentVO documentVO) { FileOutputStream file = null; try { // 检查文件路径 this.checkFile(new File(absolutePath)); absolutePath = absolutePath + "//" + documentVO.getFileName() + "." + documentVO.getFileType(); file = new FileOutputStream(absolutePath); int length = 0; byte[] buffer = new byte[10240]; while ((length = in.read(buffer, 0, 10240)) > -1) { file.write(buffer, 0, length); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (in != null) in.close(); if (file != null) file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 把输出流对象持久化 * @param in */ public void write(OutputStream out,String absolutePath,DocumentVO documentVO) { FileOutputStream file = null; try { // 检查文件路径 this.checkFile(new File(absolutePath)); absolutePath = absolutePath + "//" + documentVO.getFileName() + "." + documentVO.getFileType(); file = new FileOutputStream(absolutePath); ByteArrayOutputStream baos = (ByteArrayOutputStream)out; file.write(baos.toByteArray()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (out != null) out.close(); if (file != null) file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 检查文件的路径是否存在,如果不存在则创建该路径,以便创建该文件 * * @param file */ private void checkFilePath(File file) { this.checkFile(file.getParentFile()); } /** * 检查路径 * @param file * 路径的最后一个节点, 如C:/1/2/3/d.file 则将该File对象的.getParentFile传入 即C:/1/2/3 */ private void checkFile(File file) { //如果该文件对象不存在 if(!file.exists()) { //如果文件对象不存在,则继续查询其父类的文件对象,并创建目录 this.checkFilePath(file.getParentFile()); file.mkdir(); } } /** * 这边记录已上传文件的序列号 * @param documentVO * @throws Exception */ public void logSequenceNumber(DocumentVO documentVO) throws Exception { if(documentVO != null && !"".equals(documentVO)) { if(documentVO.getSequenceNumber() != null && !"".equals(documentVO.getSequenceNumber())) { String sequenceNumber = documentVO.getSequenceNumber() + ","; this.logSeqToFile(sequenceNumber); } } } /** * 把传递进来的序列号加入到文件的最后端,按照英文状态下的,分隔 * @param sequenceNumber * @throws IOException */ private void logSeqToFile(String sequenceNumber) throws IOException { //这边先写死了一个路径,正确的应该是写在配置文件中的 String path = "D://Workspace//DocumentUpload//node.txt"; File file = new File(path); FileOutputStream out = new FileOutputStream(file,true); byte[] byte1 = new byte[512]; int b = sequenceNumber.length(); //这边需要写入字节 out.write(sequenceNumber.getBytes()); out.close(); } /** * 读取记录文件中的内容并返回 * @return * @throws Exception */ public String getLogFile() throws Exception { String str = ""; //这边先写死了一个路径,正确的应该是写在配置文件中的 String path = "D://Workspace//DocumentUpload//node.txt"; File file = new File(path); BufferedReader b = new BufferedReader(new FileReader(file)); String i; while((i = b.readLine()) != null) { str += i; } return str; } }

     

     5.  文档压缩类 ZipUtil

     

       package doc.util; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; /** * 对文档进行压缩的类 * @author linwei * */ public class ZipUtil { // 要压缩文件的最大值 public final static long maxSize = 100000000;// 这个可以配置到配置文件中 100MB public final static int BUFFERSIZE = 2048 ; // private static final ThreadLocal currentZipName = new ThreadLocal(); /** * 根据输出路径对文件流进行压缩输出 * @param fileOutPath * @param mapInputStreams * @throws Exception */ public void zip(String fileOutPath, Map mapInputStreams) throws Exception { if (fileOutPath == null || "".equals(fileOutPath)) { return; } if (mapInputStreams != null && mapInputStreams.size() > 0) { Set entrys = mapInputStreams.entrySet(); FileOutputStream out = new FileOutputStream(fileOutPath); //Java压缩专用类 ZipOutputStream zip = new ZipOutputStream(out); String fileName = null; InputStream inputStream = null; Iterator it = entrys.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); fileName = (String) entry.getKey(); inputStream = (InputStream) entry.getValue(); zip(zip, inputStream, fileName); } zip.close(); } } /** * 压缩文件 * @param out * @param inputStream * @param fileName * @throws Exception */ private void zip(ZipOutputStream out, InputStream inputStream, String fileName) throws Exception { //for test /*File file1 = new File("D://Workspace//DocumentUpload//","test.txt"); BufferedOutputStream out1 = new BufferedOutputStream(new FileOutputStream(file1)); int b; byte[] buf = new byte[2048]; while((b = inputStream.read(buf)) != -1) { out1.write(buf); } //注意,这边三点最好全部都写完整,要不会出问题 //将缓冲区中的数据全部写出。 out1.flush(); inputStream.close(); out1.close();*/ //for test //开始写入新的 ZIP 文件条目并将流定位到条目数据的开始处 //********************************************** //这边请注意,ZipOutputStream和ZipEntry都请用org.apache.tools.zip包下的类, //这样就可以解决压缩文件名乱码的问题了。 out.putNextEntry(new org.apache.tools.zip.ZipEntry(fileName)); int b1; byte[] buf1 = new byte[BUFFERSIZE]; while ((b1 = inputStream.read(buf1)) != -1) { out.write(buf1, 0, b1); } if (inputStream != null) { inputStream.close(); inputStream = null; } } }

     

    6.  文档的实体类 DocumentVO

      package upload; /** * 用来传递参数的 * @author linwei * */ public class DocumentVO { private String fileName; private String sequenceNumber; private String fileType; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(String sequenceNumber) { this.sequenceNumber = sequenceNumber; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } }

     

     

    7.  文档调阅界面

     

      <%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <%@ page import="upload.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'docUpload.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" mce_href="styles.css"> --> <mce:script type="text/javascript" src="resources/jquery.js" mce_src="resources/jquery.js"></mce:script> <mce:script type="text/javascript" src="resources/upload/fileUploadUtil.js" mce_src="resources/upload/fileUploadUtil.js"></mce:script> </head> <body> <% FileOperation f = new FileOperation(); String str = f.getLogFile(); String[] s = str.split(","); %> <form action="" name="form1"> <table id="upload" border="1"> <tr> <td width="20%">文档连接</td> </tr> <% for(int i=0;i<s.length;i++) { %> <tr> <td><a href="/AJAX/servlet/fileDownload?id=<%=s[i]%>"><%=s[i] %></a></td> </tr> <% } %> </table> </form> </body> </html>

     

     

    8.  调阅Servlet

     

      package upload; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 文档下载服务类 * @author linwei * */ public class fileDownload extends HttpServlet { /** * Constructor of the object. */ public fileDownload() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); this.doDownload(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost"); this.doDownload(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } /** * 此方法被doPost和doGet方法调用,用来统一调用文档 * @param request * @param response * @throws ServletException * @throws IOException */ public void doDownload(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{ InputStream in = null; response.setContentType("application/x-download; charset=gb2312"); //取得文件分割符 String file_separator = System.getProperty( "file.separator" ); //这边自己假设一个显示的文件名 String displayname = "temp111.zip"; //这边路径也是先写死的,后面可以改 String path = "D://Workspace//DocumentUpload//" + request.getParameter("id"); response.addHeader("Content-Disposition","attachment;filename=" + new String(displayname.getBytes("gb2312"),"iso-8859-1")); try { in = new FileInputStream(path); this.downLoad(in, response); } catch(Exception e) { } finally { if(in != null) in.close(); } } /** * write file stream to servlet output stream * @param is * @param response * @throws Exception */ private void downLoad(InputStream in, HttpServletResponse response) throws Exception { BufferedInputStream bufferInput = new BufferedInputStream(in); ServletOutputStream out = null; try { byte[] buffer = new byte[10240]; out = response.getOutputStream(); int len; while((len = bufferInput.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); response.setStatus(response.SC_OK); response.flushBuffer(); } catch(Exception e) { throw e; } finally { if (out != null) { out.close(); } if (bufferInput != null) { bufferInput.close(); } if (in != null) { in.close(); } } } }

     

     

     以上只是一些简单的过程,具体的一些信息还是需要按照不同的需求进行修改的。

     

     

     

     

      

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     


    最新回复(0)