Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Struts2 一次上傳多個檔案:完整實作步驟

需要一次送出多張圖片時,Struts2 只要把表單與 Action 的屬性都改成陣列即可,不必額外寫檔案處理邏輯。

第一步:補上相依套件

把 commons-fileupload-1.2.1.jar 與 commons-io-1.32.2.jar 放進 WEB-INF/lib。

第二步:撰寫表單

<form action="${pageContext.request.contextPath}/control/employee/list_execute.action"
      enctype="multipart/form-data" method="post">
    文件1: <input type="file" name="image"><br/>
    文件2: <input type="file" name="image"><br/>
    文件3: <input type="file" name="image"><br/>
    <input type="submit" value="上傳"/>
</form>

關鍵在於 enctype="multipart/form-data" 與 method="post" 這兩個固定值,少一個都收不到檔案。另外三個 file 控件的 name 全部相同,都是 image。

第三步:Action 用陣列接收

public class HelloWorldAction {
    private File[] image;              // 上傳的檔案
    private String[] imageFileName;    // 檔名
    private String[] imageContentType; // 檔案型別

    public File[] getImage() { return image; }
    public void setImage(File[] image) { this.image = image; }

    public String[] getImageFileName() { return imageFileName; }
    public void setImageFileName(String[] imageFileName) { this.imageFileName = imageFileName; }

    public String[] getImageContentType() { return imageContentType; }
    public void setImageContentType(String[] imageContentType) { this.imageContentType = imageContentType; }

    public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        if (image != null) {
            File savedir = new File(realpath);
            if (!savedir.exists()) savedir.mkdirs();
            for (int i = 0; i < image.length; i++) {
                File savefile = new File(savedir, imageFileName[i]);
                FileUtils.copyFile(image[i], savefile);
            }
            ActionContext.getContext().put("message", "上傳成功");
        }
        return "success";
    }
}

要特別注意:Action 中的 image 屬性名稱必須和表單上傳控件的 name 完全一致,否則框架無法完成對應;檔名與型別 likewise 要成對出現,才能正確還原每一個檔案。

Copyright © Linux教程網 All Rights Reserved