1. 程式人生 > >java實現大檔案的上傳

java實現大檔案的上傳

 最近專案經理逼著讓偶做樹的展開,表巢狀表,可惜偶剛參加工作,水平低,這不在查資料嘛,可是不多久就傳來了經理的叫囂聲,這麼簡單的東西,都一天了,你還沒做完..................,哎真是鬱悶,誰讓咱水平低呢(心想,什麼時候等我水平提高了,看我怎麼收拾你,又一想,等我水平提高了,人家早不知道幹什麼去了,廢話不多說了)

檔案上傳一直是B/S結構中很重要的一項功能,在java中並沒有很好的實現檔案上傳的類包,因此出現了一些開源的元件,Smartupload ,commons-fileupload,還有國內的一個"牛人"的(不好意思叫不上名字來),這幾個元件中Smartupload 出來的時候應該最早,不過現在已經不再有新的版本出現,還有一個不足的地方就是Smartupload 支援上傳的檔案最大在100M左右,這可滿足不了客戶的需求,聽說commons-fileupload不錯,經過幾番測試終於搞定,下面是程式碼,3個jsp檔案 upload.jsp success.jsp error.jsp 一個action類

upload.jsp如下:

<%@ page language="java" contentType="text/html;charset=GBK"%>
<%@ page import="java.util.*" %>
<%@ page import="org.apache.commons.fileupload.*"%>

<%@ include file="/basic/include/headerjsf1.jsp" %>

<%pageContext.setAttribute("jsp.tags.reuse", new Boolean(false));%>
<A:navigation/>
<hr>
<center><b><font size=+1><bean:message key="upload.name"/></font></b></center>
<html>
<head>
 <title>????</title>
</head>
<body>

<form action="/budget3/FileUploadAction.do" name="one" enctype="multipart/form-data" method="post">

<p align="center">檔案上傳
  <input type="File" name="fileupload" value="upload" />
  <input type="submit" value="上傳">
  <input type="reset" value="取消">
  </p>
</form>
</body>
</html>

很簡單,在選擇上傳檔案後,此頁面會轉向FileUploadAction.do,這個類負責完成檔案的上傳功能,具體程式碼如下:

package com.atools.budget.TestTree.action;

import  com.atools.ggcw.action.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.commons.fileupload.*;
import org.apache.commons.io.*;
import java.io.*;
import java.util.*;
/**
 * @author hh
 *
 */
public class FileUploadAction extends BaseAction {
 public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response )
 {
  ActionForward forward=null;
  try
  {
  
   System.out.println("start");
   DiskFileUpload upload=new DiskFileUpload();
   List uploadlist=upload.parseRequest(request);
//   System.out.println("list  is "+uploadlist);
   Iterator iter=uploadlist.iterator();
   while(iter.hasNext())
   {
    FileItem  item=(FileItem)iter.next();
    if(!item.isFormField())
    {
     String filename=item.getName();
     filename=FilenameUtils.getName(filename);
     if(!filename.equals(""))
     {
      System.out.println("start"+filename);
      String savepath="D://temp//"+filename;
      System.out.println("savepath is "+savepath);
      File saveFilepath=new File(savepath);
      item.write(saveFilepath);
      forward=mapping.findForward("success");
     }else
      forward=mapping.findForward("error");
     
    }
   } 
   
  }catch(Exception ex)
  {
   ex.printStackTrace();
   System.out.println("程式發生錯誤,丟擲異常為 "+ex.getMessage());
  }
  
  return forward;
 }
}
兩個轉向頁面success.jsp和error.jsp很簡單,這裡就不寫了.作者測試了一下上傳200M的檔案很快就完成了,而Smartupload 的根本實現不了200M左右檔案的上傳

在筆者查資料的時候,發現很多都是這樣寫的

<%@ page language=“java”contentType=“text/html;charset=GBK”%>
<%@ page import=“java.util.*”%>
<%@ page import=“org.apache.commons.fileupload.*”%>
<html>
<head>
<title>檔案上傳</title>
</head>
<%
 DiskFileUpload fu = new DiskFileUpload();
 // 設定允許使用者上傳檔案大小,單位:位元組
 fu.setSizeMax(10000000);
 // 設定最多隻允許在記憶體中儲存的資料,單位:位元組
 fu.setSizeThreshold(4096);
 // 設定一旦檔案大小超過getSizeThreshold()的值時資料存放在硬碟的目錄
 fu.setRepositoryPath(“D://Tomcat5//TEMP”);
 //開始讀取上傳資訊
 List fileItems = fu.parseRequest(request);
 // 依次處理每個上傳的檔案
 Iterator iter = fileItems.iterator();
 while (iter.hasNext()) {
  FileItem item = (FileItem) iter.next();
  //忽略其他不是檔案域的所有表單資訊
  if (!item.isFormField()) {
   String name = item.getName();
   item.write(“D://UploadTest//”+ name);
 }
}
%>

其中直接得到檔名 item.getName();

然後將其寫入item.write(“D://UploadTest//”+ name);是不對的,因為item.getName()得到的檔名是包括上傳路徑的,比如E:/work.doc,在寫入的時候D://UploadTest/+E:/work.doc肯定是不對的,還有一點例項item的write()方法要求傳入的引數為File類的例項.

裡面有很多東西還在琢磨,有知道的朋友也可以交流