1. 程式人生 > >Java中實現檔案上傳下載的三種解決方案

Java中實現檔案上傳下載的三種解決方案

第一點:Java程式碼實現檔案上傳

  FormFile file=manform.getFile(); 
  String newfileName = null;
  String newpathname=null;
  String fileAddre="/numUp";
  try {
   InputStream stream = file.getInputStream();// 把檔案讀入
    String filePath = request.getRealPath(fileAddre);//取系統當前路徑
          File file1 = new File(filePath);//添加了自動建立目錄的功能
       ((File) file1).mkdir();   
    newfileName = System.currentTimeMillis()
     + file.getFileName().substring(
       file.getFileName().lastIndexOf('.'));
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   OutputStream bos = new FileOutputStream(filePath + "/"
     + newfileName);
   newpathname=filePath+"/"+newfileName;
   System.out.println(newpathname);
   // 建立一個上傳檔案的輸出流
    System.out.println(filePath+"/"+file.getFileName());
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
    bos.write(buffer, 0, bytesRead);// 將檔案寫入伺服器
   }
   bos.close();
   stream.close();
    } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

第二點:Jsp頁面上實現檔案上傳

package com.vogoal.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
public class JspFileUpload {
    /** request物件 */
    private HttpServletRequest request = null;
    /** 上傳檔案的路徑 */
    private String uploadPath = null;
    /** 每次讀取得位元組的大小 */
    private static int BUFSIZE = 1024 * 8;
    /** 儲存引數的Hashtable */
    private Hashtable paramHt = new Hasptable();
    /** 儲存上傳的檔案的檔名的ArrayList */
    private ArrayList updFileArr = new ArrayList();
    /**
     * 設定request物件。
     * 
     * @param request
     *            HttpServletRequest request物件
     */
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }
    /**
     * 設定檔案上傳路徑。
     * 
     * @param path
     *            使用者指定的檔案的上傳路徑。
     */
    public void setUploadPath(String path) {
        this.uploadPath = path;
    }
    /**
     * 檔案上傳處理主程式。�������B
     * 
     * @return int 操作結果 0 檔案操作成功;1 request物件不存在。 2 沒有設定檔案儲存路徑或者檔案儲存路徑不正確;3
     *         沒有設定正確的enctype;4 檔案操作異常。
     */
    public int process() {
        int status = 0;
        // 檔案上傳前,對request物件,上傳路徑以及enctype進行check。
        status = preCheck();
        // 出錯的時候返回錯誤程式碼。
        if (status != 0)
            return status;
        try {
            // ��引數或者檔名�u��
            String name = null;
            // 引數的value
            String value = null;
            // 讀取的流是否為檔案的標誌位
            boolean fileFlag = false;
            // 要儲存的檔案。
            File tmpFile = null;
            // 上傳的檔案的名字
            String fName = null;
            FileOutputStream baos = null;
            BufferedOutputStream bos = null;
            // ��儲存引數的Hashtable
            paramHt = new Hashtable();
            updFileArr = new ArrayList();
            int rtnPos = 0;
            byte[] buffs = new byte[BUFSIZE * 8];
            // �取得ContentType
            String contentType = request.getContentType();
            int index = contentType.indexOf("boundary=");
            String boundary = "--" + contentType.substring(index + 9);
            String endBoundary = boundary + "--";
            // �從request物件中取得流。
            ServletInputStream sis = request.getInputStream();
            // 讀取1行
            while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) {
                String strBuff = new String(buffs, 0, rtnPos);
                // 讀取1行資料�n��
                if (strBuff.startsWith(boundary)) {
                    if (name != null && name.trim().length() > 0) {
                        if (fileFlag) {
                            bos.flush();
                            baos.close();
                            bos.close();
                            baos = null;
                            bos = null;
                            updFileArr.add(fName);
                        } else {
                            Object obj = paramHt.get(name);
                            ArrayList al = new ArrayList();
                            if (obj != null) {
                                al = (ArrayList) obj;
                            }
                            al.add(value);
                            System.out.println(value);
                            paramHt.put(name, al);
                        }
                    }
                    name = new String();
                    value = new String();
                    fileFlag = false;
                    fName = new String();
                    rtnPos = sis.readLine(buffs, 0, buffs.length);
                    if (rtnPos != -1) {
                        strBuff = new String(buffs, 0, rtnPos);
                        if (strBuff.toLowerCase().startsWith(
                                "content-disposition: form-data; ")) {
                            int nIndex = strBuff.toLowerCase().indexOf(
                                    "name=\"");
                            int nLastIndex = strBuff.toLowerCase().indexOf(
                                    "\"", nIndex + 6);
                            name = strBuff.substring(nIndex + 6, nLastIndex);
                        }
                        int fIndex = strBuff.toLowerCase().indexOf(
                                "filename=\"");
                        if (fIndex != -1) {
                            fileFlag = true;
                            int fLastIndex = strBuff.toLowerCase().indexOf(
                                    "\"", fIndex + 10);
                            fName = strBuff.substring(fIndex + 10, fLastIndex);
                            fName = getFileName(fName);
                            if (fName == null || fName.trim().length() == 0) {
                                fileFlag = false;
                                sis.readLine(buffs, 0, buffs.length);
                                sis.readLine(buffs, 0, buffs.length);
                                sis.readLine(buffs, 0, buffs.length);
                                continue;
                            }else{
                                fName = getFileNameByTime(fName);
                                sis.readLine(buffs, 0, buffs.length);
                                sis.readLine(buffs, 0, buffs.length);
                            }
                        }
                    }
                } else if (strBuff.startsWith(endBoundary)) {
                    if (name != null && name.trim().length() > 0) {
                        if (fileFlag) {
                            bos.flush();
                            baos.close();
                            bos.close();
                            baos = null;
                            bos = null;
                            updFileArr.add(fName);
                        } else {
                            Object obj = paramHt.get(name);
                            ArrayList al = new ArrayList();
                            if (obj != null) {
                                al = (ArrayList) obj;
                            }
                            al.add(value);
                            paramHt.put(name, al);
                        }
                    }
                } else {
                    if (fileFlag) {
                        if (baos == null && bos == null) {
                            tmpFile = new File(uploadPath + fName);
                            baos = new FileOutputStream(tmpFile);
                            bos = new BufferedOutputStream(baos);
                        }
                        bos.write(buffs, 0, rtnPos);
                        baos.flush();
                    } else {
                        System.out.println("test :" + value + "--" + strBuff);
                        value = value + strBuff;
                    }
                }
            }
        } catch (IOException e) {
            status = 4;
        }
        return status;
    }
    private int preCheck() {
        int errCode = 0;
        if ( request == null )
            return 1;
        if ( uploadPath == null || uploadPath.trim().length() == 0 )
            return 2;
        else{
            File tmpF = new File(uploadPath);
            if (!tmpF.exists())
                return 2;
        }
        String contentType = request.getContentType();
        if ( contentType.indexOf("multipart/form-data") == -1 )
            return 3;
        return errCode;
    }
    public String getParameter(String name){
        String value = "";
        if ( name == null || name.trim().length() == 0 )
            return value;
        value = (paramHt.get(name) == null)?"":(String)((ArrayList)paramHt.get(name)).get(0);
        return value;
    }
    public String[] getParameters(String name){
        if ( name == null || name.trim().length() == 0 )
            return null;
        if ( paramHt.get(name) == null )
            return null;
        ArrayList al = (ArrayList)paramHt.get(name);
        String[] strArr = new String[al.size()];
        for ( int i=0;i<al.size();i++ )
            strArr[i] = (String)al.get(i);
        return strArr;
    }
    
    public int getUpdFileSize(){
        return updFileArr.size();
    }
    
    public String[] getUpdFileNames(){
        String[] strArr = new String[updFileArr.size()];
        for ( int i=0;i<updFileArr.size();i++ )
            strArr[i] = (String)updFileArr.get(i);
        return strArr;
    }
    private String getFileName(String input){
        int fIndex = input.lastIndexOf("\\");
        if (fIndex == -1) {
            fIndex = input.lastIndexOf("/");
            if (fIndex == -1) {
                return input;
            }
        } 
        input = input.substring(fIndex + 1);
        return input;
    }
    private String getFileNameByTime(String input){
        int index = input.indexOf(".");
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return input.substring(0,index) + sdf.format(dt) + input.substring(index);
    }
}

2.在Jsp頁面中進行引用該Java類:

<%@page import="com.vogoal.util.JspFileUpload"%>

<%
    //初始化
    JspFileUpload jfu = new JspFileUpload();
    //設定request物件
    jfu.setRequest(request);
    //設定上傳的檔案路徑
    jfu.setUploadPath("C:\\");
    //上傳處理
    int rtn = jfu.process();
    //取得form中其他input控制元件引數的值
    String username = jfu.getParameter("username");
    //如果對應同一個引數有多個input控制元件,返回陣列
    String[] usernameArr = jfu.getParameters("username");
    //取得上傳的檔案的名字
    String[] fileArr = jfu.getUpdFileNames();
    //取得上傳檔案的個數,這個方法有點雞肋
    int fileNumber = jfu.getUpdFileSize();
//下面的是測試輸出的程式碼。
//       out.println("parameter:" + username);
//       out.println("parameter size:" + usernameArr.length);
//       out.println("fileArr size:" + fileArr.length);
//       if (fileArr.length > 0)
//              out.println("fileArr 0:" + fileArr[0]);
%>

第三點:struts2實現檔案的上傳和下載

第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。這兩個檔案可以從http://commons.apache.org/下載。

第二步:把form表的enctype設定為:“multipart/form-data“,如下:


Java程式碼 public class UploadAction{  

  private File uploadImage; //檔案  

  private String uploadImageContentType;//檔案的型別  

  private String uploadImageFileName;//檔案的名稱  

  private String bookname;//書名  

  private String author;//作者  

  private String savePath;//檔案的儲存位置  

  //屬性的getter/setter方法  

  public String upload() throws Exception{  

             //實現上傳程式碼,I/O操作完成  

  return "uploadSuccess";  

  }  

}  
複製程式碼注:一個表單裡的檔案域對應Action中三個屬性,分別是檔案,檔名,檔案型別,命名是固定的,檔名必須表單中的檔案域名稱相同(uploadImage),檔名為:檔案+FileName,檔案型別:檔案+ContentType。

第四步:將我們的上傳Action配置到struts.xml中。


Java程式碼 <action name="upload" class="com.gqy.UploadAction">  

      <param name="savePath">/uploadFile</param>  

      <result>/success.jsp</result>  

</action>  
複製程式碼注:
指定上傳檔案的在伺服器上的儲存目錄,需要在UploadAction中為定義savePath變數併為其新增相應的setter和getter方法,便於Struts2將/uploadFile值賦給savePath屬性,即要想在UploadAction中使用savePath變數必須在UploadAction定義。

手動配置檔案過濾型別

Java程式碼 <param name="allowTypes">  

    image/bmp,image/png,image/gif,image/jpeg  

</param> 
複製程式碼手動配置檔案大小限制

Java程式碼 <param name="maximumSize" >1048576</param>  
複製程式碼使用Struts2的檔案上傳攔截器實現檔案過濾


Struts2提供了一個檔案上傳的攔截器—fileUpload,通過配置該攔截器可以方便實現上傳檔案的過濾。
配置fileUpload攔截器時,可以為其指定兩個引數:
 allowedTypes:指定允許上傳的檔案型別,多個檔案型別之間以英文逗號(,)隔開。
 maximumSize:指定允許上傳的檔案大小,單位是位元組。
提示:通過配置fileUpload攔截器,可以輕鬆的實現文過濾,當檔案過濾失敗後,系統自動轉入input邏輯檢視,因此必須為該Action配置名為input的邏輯檢視,除此之外,還必須顯示地為該Action配置defaultStack的攔截器引用。

使用Struts2的攔截器實現檔案過濾配置如下:


使用Struts2的攔截器實現檔案過濾配置如下:

Java程式碼 <action name="uploadFileAction" class="com.actions.UploadFileAction">  

          <interceptor-ref name="defaultStack">  

              <!-- 配置允許上傳的檔案型別,多個用","分隔 -->                   

              <param name="fileUpload.allowedTypes">                       

                    image/bmp,image/png,image/gif,image/jpeg,image/jpg   

                    ,image/x-png, image/pjpeg  

              </param>                  

              <!-- 配置允許上傳的檔案大小,單位位元組,本例為:1MB -->  

              <param name="fileUpload.maximumSize">1048576</param>  

          </interceptor-ref>  

          <result name="input">/jsp/oneFileFileupload.jsp</result>  

          <result name="success">/jsp/result.jsp</result>  

</action>  
複製程式碼當用戶上傳失敗後,需要有一定的提示資訊。在Struts2中,使用<s:fielderror/>標籤即可將錯誤提示資訊輸出到頁面中。
注:要想使用Struts2錯誤提示資訊,則上傳檔案的Action類,必須繼承ActionSupport,否則Struts2不會提供輸出錯誤提示資訊功能。

我們可以配置資原始檔(.properties)來儲存輸出給使用者的資訊。

struts.messages.eror.file.too.large:當上傳檔案大小超過設定的值時,Struts2將輸出該key對應的提示資訊。
struts.messages.error.content.type.not.allowed:當上傳檔案型別不符合設定的值時,Struts2將輸出該key對應的提示資訊。
struts.messages.error.uploading:當上傳檔案時出現未知錯誤時,Struts2將輸出該key對應的提示資訊。

我們還要將資原始檔配置到struts.xml檔案中,接下來看看我們的資原始檔,已經包含中文了,得把它進行一下轉換再配置到工程中。
在struts.xml中設定資原始檔:


<constant name="struts.custom.i18n.resources" value="messages"/>或
<constant name="struts.custom.i18n.resources" value="messages_zh_CN"/>

用命令native2ascii  d:\messages.properties d:\messages_zh_CN.properties將原有的資原始檔轉換成支援中的。

注:保持國際化,資原始檔的名稱字尾為: *_zh_CN+副檔名的形式。


對於多個檔案上傳的原理同上,但是需要注意的是,多個檔案域的name屬性名必須相同,而且在Action中應該使用File [] 或者List<File>來接收。

個人覺得用這樣的方式進行多個檔案上傳不是

很好。


Struts2進行檔案下載


Struts2提供了stream結果型別,該結果型別專門用於支援檔案下載的功能。當指定stream結果型別時,需要配置一個inputName引數,該引數指定了一個輸入流,這個輸入流是被下載檔案的入口(即通過該入口才能實現檔案以流的方式實現下載)。


實現檔案下載的Action

Java程式碼 public class FileDownloadAction implements Action{  

   //該屬性值在配置檔案中指定,Struts2會自動進行注入(即賦值),需要為該屬性提供setter和 getter方法  

   private String inputPath;//指定要下載的檔案的完整路徑(路徑名+檔名)  

   /* 

     * 實現下載的Action類應該提供一個返回InputStream例項的方法,該方法對應在       

        <result.../>裡的inputName屬性值為targetFile 

   */ 

   public InputStream getTargetFile() throws Exception{  

      return  ServletActionContext.getServletContext().getResourceAsStream(inputPath);  

   }  

   //處理使用者請求的execute方法,該方法返回success字串  

   public String execute() throws Exception{  

      return "success";  

   }  

}  
複製程式碼對應Action在struts.xml檔案中的配置

Java程式碼 <action name="download" class="com.FileDownloadAction">

   <!--指定被下載資源的位置-->

      <param name="inputPath">/uploadFile/demo.txt</param>

   <!--配置結果型別為stream的結果-->

   <result name="success" type="stream">

       <!--指定下載檔案的檔案型別-->

          <param name="contentType"></param>

       <!--指定下載檔案的檔案位置-->

          <param name="inputName">targetFile</param>

       <!--指定下載檔案的下載方式及下載時的儲存檔名,filename儲存時的檔名必須有副檔名,副檔名指示了下載型別的圖示-->

          <param name="contentDisposition">

                attachment;filename=Struts2.txt

          </param>

       <!--指定下載檔案的緩衝區大小-->

          <param name="bufferSize">4096</param>

   </result>

</action>