struts2實現檔案上傳、多檔案上傳和檔案下載

來源:互聯網
上載者:User

標籤:style   io   ar   os   使用   sp   java   for   on   

總結的兩個問題,就是struts2上傳下載的時候對屬性名稱配置要求非常嚴格:

第一:上傳的時候

    private File file;

    private String fileContentType;

private String fileFileName;

屬性的紅色部分必須有可以隨意起,但不能省略。

第二:下載的時候屬性名稱不能隨意起。

 

 

實現檔案上傳:可以找到WEB-INF\lib\struts2-core-2.3.16.3.jar下的struts-default.xml裡的攔截器標籤下的name=fileUpload的實體類alt+shift+t進去原始碼(前提是關聯好jar包),看看

 

我的上傳Action:

package cn.jbit.action;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

 

import org.apache.struts2.ServletActionContext;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class UploadAction extends ActionSupport {

//Action中使用了3個屬性來封裝檔案資訊

//1:File類型的xxx屬性:與表單中的File控制項的name屬性一致,用於封裝File控制項對應的檔案內容

//2:String類型的xxxFileName屬性和3:String類型的xxxContentType屬性,這兩個屬性的固定文法是

//File類型的屬性名稱+尾碼FileName|ContentType組合成最終:xxxFileName,xxxContentType

//如果不按固定文法寫的話,可能會造成檔案名稱和檔案類型讀取不到的情況,最終寫入的檔案是一個

//名字為:null,並且沒有類型格式的檔案資訊。(雖然手動改成.jpg也會顯示) private File file;

    private String fileContentType;

    private String fileFileName;

@Override

public String execute() throws Exception {

//1024*1024=1M

  byte[] buffer=new byte[1024*1024];

  //表單裡的file標籤

  InputStream fis=new FileInputStream(file);

  //在WebRoot目錄下建立一個存放圖片的檔案夾,然後擷取真實的地址

  String path=ServletActionContext.getServletContext().getRealPath("image");

  path=path+"\\"+this.fileFileName;

  System.out.println(path);

  //最終把讀到的二進位流都寫入,真真實位址下同名的檔案裡

  OutputStream os=new FileOutputStream(path);

  //OutputStream os=new FileOutputStream("E:\\upload\\"+this.fileFileName);

  int len=0;

  while((len=fis.read(buffer))>0){

  os.write(buffer,0,len);

  }

  fis.close();

  os.close();

return SUCCESS;

}

public File getFile() {

return file;

}

public void setFile(File file) {

this.file = file;

}

public String getFileContentType() {

return fileContentType;

}

public void setFileContentType(String fileContentType) {

this.fileContentType = fileContentType;

}

public String getFileFileName() {

return fileFileName;

}

public void setFileFileName(String fileFileName) {

this.fileFileName = fileFileName;

} 

}

上傳完之後,切記就是此時如果你在WebRoot下右鍵開啟image→MyEclipse→open in Explorer是找不到你上傳的圖片的,因為圖片真實的儲存地址是在項目部署的地方webapps裡如:E:\Program Files (x86)\apache-tomcat-7.0.55\webapps\up\image而不是這個路徑:E:\java2\upload2014年12月2日\WebRoot\image。

 

上傳檔案的表單:

 <body>

      <s:form action="upload" enctype="multipart/form-data" method="post">

      <s:file name="file" label="選擇檔案"></s:file>

      <s:submit value="上傳"></s:submit>

      </s:form>

  </body>

成功後跳轉的頁面:

      您所上傳的檔案是:<s:property value="fileFileName"/><br/>

      檔案類型:<s:property value="fileContentType"/><br/>。

上傳多個檔案的話:

我們在WEB-INF\lib\struts2-core-2.3.16.3.jar下的org.apache.struts2下的default.properties裡搜尋max能看到:

struts.multipart.maxSize=2097152

也就是struts2裡給的預設上傳大小是2M(上傳多個檔案總大小),那麼我們可以在struts2.xml裡面設定大點:

 //20M

 <constant name="struts.multipart.maxSize" value="20971520"/>

我的上傳表單為:

      <s:form action="upload" enctype="multipart/form-data" method="post">

      <s:file name="files" label="選擇檔案"></s:file>

      <s:file name="files" label="選擇檔案"></s:file>

      <s:file name="files" label="選擇檔案"></s:file>

      <s:file name="files" label="選擇檔案"></s:file>

      <s:file name="files" label="選擇檔案"></s:file>

      <s:file name="files" label="選擇檔案"></s:file>

      <s:submit value="上傳"></s:submit>

我的上傳Action:

package cn.jbit.action;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

private static final long serialVersionUID = 1L;

    private File[] files;

    private String[] filesContentType;

    private String[] filesFileName;

@Override

public String execute() throws Exception {

byte[] buffer=new byte[1024*1024];

files=getFiles();

for (int i = 0; i < files.length; i++) {

  //表單裡的file標籤

  InputStream fis=new FileInputStream(files[i]);

  //在WebRoot目錄下建立一個存放圖片的檔案夾,然後擷取真實的地址

  String path=ServletActionContext.getServletContext().getRealPath("image");

  path=path+"\\"+this.filesFileName[i];

  System.out.println(path);

  //最終把讀到的二進位流都寫入,真真實位址下同名的檔案裡

              OutputStream os=new FileOutputStream(path);

  int len=0;

  while((len=fis.read(buffer))>0){

  os.write(buffer,0,len);

  }

  fis.close();

  os.close();

}

 

return SUCCESS;

}

 

public File[] getFiles() {

return files;

}

public void setFiles(File[] files) {

this.files = files;

}

public String[] getFilesContentType() {

return filesContentType;

}

 

 

   public void setFilesContentType(String[] filesContentType) {

this.filesContentType = filesContentType;

}

public String[] getFilesFileName() {

return filesFileName;

}

public void setFilesFileName(String[] filesFileName) {

this.filesFileName = filesFileName;

}

}

實現檔案下載:

我的Action:

package cn.jbit.action;

 

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStream;

 

import org.apache.struts2.ServletActionContext;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class FileDownAction extends ActionSupport {

//struts2對屬性名稱的配置很嚴格,如果不正確是會報錯的,我在這裡犯了個錯

   //把private InputStream InputStream ;聲明成了InputStream input;

   //就給我報錯說找不到inputStream,所以建議 //fileName,contentType,inputStream屬性名稱不要自己隨便起名。

 

 

對常用的屬性名稱來說比如

//讀取下載檔案的目錄

private String path;

//下載檔案的檔案名稱

private String fileName;

//下載檔案的類型

private String contentType;

//讀取下載檔案的輸入資料流

private InputStream inputStream;

 

 

 

 

@Override

public String execute() throws Exception {

return SUCCESS;

}

public String getFileName() {

return fileName;

}

public void setFileName(String fileName) {

this.fileName = fileName;

}

public String getContentType() {

return contentType;

}

public void setContentType(String contentType) {

this.contentType = contentType;

}

public InputStream getInputStream() throws FileNotFoundException {

String paths=ServletActionContext.getServletContext().getRealPath(path);

return new BufferedInputStream(new FileInputStream(paths+"\\"+fileName));

}

public void setInputStream(InputStream inputStream) {

this.inputStream = inputStream;

}

public String getPath() {

return path;

}

public void setPath(String path) {

this.path = path;

}

}

我的struts.xml配置:

<action name="download" class="cn.jbit.action.FileDownAction" >

            <param name="path">/image</param>

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

               <!-- 找到發行伺服器Tomcat下→conf→web.xml裡有各種各樣的mime類型 -->

               <!-- mime:多用途互連網郵件擴充類型,是設定某種副檔名的檔案用一種應用程式來開啟的方式類型 -->

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

               <param name="fileName">input</param>

               <param name="contentDisposition">

                <!-- contentDisposition參數由兩部分組成,前面的部分標識處理檔案的形式,如attachment表示在下載時彈出對話方塊,提示使用者儲存或者直接開啟該檔案;

                   後一部分標識下載檔案的檔案名稱,量部分之間以分號進行分割 -->                         

                    attachment;filename="${fileName}"

               </param>

               <!-- 設定 下載時緩衝區的大小,由於是從伺服器裡下載,建議不要設定太大 -->

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

             </result>

        </action>

 

我的down.jsp:

 <a href="download.action?fileName=Hydrangeas.jpg">點擊此處下載文檔</a>

 

struts2實現檔案上傳、多檔案上傳和檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.