struts2實現簡單檔案上傳

來源:互聯網
上載者:User

標籤:logs   oid   print   tco   color   inpu   pre   tip   com   

struts2 在內部已經幫我們做了很多封裝的工作,我們只需要簡單的寫一些配置即可。

1 表單頁面

    <form action="${pageContext.request.contextPath }/fileupload" method="post" enctype="multipart/form-data">        <input type="file" name="filesrc" ><br>        <input type="submit" value="提交">            </form>

注意:要記住input type=file 的 name屬性值,後台會用到

 

2 FileUploadAction 類來處理檔案上傳,將上傳來的檔案存放到upload 檔案夾裡

public class FileUploadAction extends ActionSupport {    private File   filesrc;    private String filesrcFileName;    private String filesrcContentType;        public File getFilesrc() {        return filesrc;    }    public void setFilesrc(File filesrc) {        this.filesrc = filesrc;    }    public String getFilesrcFileName() {        return filesrcFileName;    }    public void setFilesrcFileName(String filesrcFileName) {        this.filesrcFileName = filesrcFileName;    }    public String getFilesrcContentType() {        return filesrcContentType;    }    public void setFilesrcContentType(String filesrcContentType) {        this.filesrcContentType = filesrcContentType;    }        public String uploadFile(){        String path = ServletActionContext.getServletContext().getRealPath("/upload");        File destFile = new File(path, filesrcFileName);        try {            FileUtils.copyFile(filesrc, destFile);        } catch (IOException e) {            e.printStackTrace();            throw new RuntimeException(e);        }                return SUCCESS;    }    }

注意:所有與上傳檔案有關的域變數命名規則開始要使用 form 表單中的name屬性值。比如要有一個檔案對象,就是filesrc,如果想知道檔案名稱,就是:filesrcFileName,其中後面的FileName是固定的。至此就可以將檔案存放到upload檔案夾中。

當然此處沒有設定檔案大小、類型等判斷。

 

3 action的配置,和一般的action配置相同。就不寫了。可以參考之前的博文。struts2開發流程及配置,域對象對資料存放區的3種方式

 

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.