文檔上傳的一個簡單界面 docUpload.jsp:javascript
- <%@ 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" onchange="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 爲上傳下載文檔都須要引入的JScss
- /**
- * 定義全局變量
- */
- 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 是上傳的Servlethtml
- 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 是文檔的操做類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. 文檔壓縮類 ZipUtilnode
- 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. 文檔的實體類 DocumentVOjquery
- 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. 文檔調閱界面web
- <%@ 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. 調閱Servletajax
- 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();
- }
- }
- }
- }