1. 程式人生 > >struts2-上傳下載檔案

struts2-上傳下載檔案

struts2的檔案上傳下載很簡單,因為有攔截器的幫助,可以省略大部分程式碼,只需要通過寫入路徑就可實現。

上傳檔案
1、表單的檔案上傳中,method必須為post,還要加個enctype=”multipart/form-data”

<form action="test/upload" method="post" enctype="multipart/form-data">
  img:<input type="file" name="img">
  img:<input type="file" name="img">
  <input type
=
"submit" value="upload"> </form>

2、uploadAction.java

public class uploadAction {
    private File[] img;
    private String[] imgFileName;//檔名,必須這樣命名,否則無法識別

    public File[] getImg() {
        return img;
    }

    public void setImg(File[] img) {
        this.img = img;
    }

    public
String[] getImgFileName() { return imgFileName; } public void setImgFileName(String[] imgFileName) { this.imgFileName = imgFileName; } public String execute(){ if(img!=null){//防止img為空時直接在瀏覽器丟擲異常 for(int i = 0;i<img.length;i++){ try
{ // String path = "f:/images"; String path = ServletActionContext.getServletContext().getRealPath("/images");//獲取伺服器下應用根目錄 File destFile = new File(path ,imgFileName[i]); System.out.println(path); FileUtils.copyFile(img[i], destFile );//向目路徑寫入檔案 } catch (IOException e) { e.printStackTrace(); } } return "success"; } return "fail"; } }

3、註冊action

<action name="upload" class="com.test3.uploadAction">
            <result>/welcome.jsp</result>
            <result name="fail">/fail.jsp</result>
           </action>

修改上傳檔案最大值:
預設常量為struts.multipart.maxSize,修改值:(一次上傳的所以檔案總共的大小)

<constant name="struts.multipart.maxSize" value="20971520" /><!--20M-->

限制上傳副檔名
action下新增:

<interceptor-ref name="defaultStack">
    <param name="fileUpload.allowedExtensions">jpg,img</param>
</interceptor-ref>

檔案下載
1、 下載請求:

<a href="test/download">image</a>

2、download.java

public class download {

    private InputStream is;//檔案輸入流,用於指定伺服器向客戶端所提供下載的檔案資源
    private String fileName;

    public InputStream getIs() {
        return is;
    }

    public void setIs(InputStream is) {
        this.is = is;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String execute(){
        fileName = "2.ico";
        is = ServletActionContext.getServletContext().getResourceAsStream("/images/"+fileName);//從應用根目錄讀取檔案
        //取出後修改成自定義的名字,多從資料庫讀取
        fileName = "image.ico";

        return "success";
    }
}

3、註冊action:

<action name="download" class="com.test3.download">
             <result type="stream">
                  <param name="contentDisposition">attachment;fileName=${fileName}</param>
                  <param name="inputName">is</param><!-- inputName可省略,其後面的預設值為inputname-->
              </result>
           </action>