struts2的上傳例子

來源:互聯網
上載者:User

參考了網上一些朋友的資料,自己寫了一個struts2的上傳例子:

工程使用的是struts2和spring3整合的的,整合部分的配置就不寫了,我匯入的包有:

struts2部分一共7個:spring3就省略了。

commons-fileupload-1.1.1.jar

commons-io-1.1.jar

commons-logging-1.0.4.jar

freemarker-2.3.8.jar

ognl-2.6.11.jar

xwork-2.0.7.jar

struts2-core-2.0.14.jar

<body>  <!-- jsp部分,body裡面寫了兩個表單,一個是fileUpload.action的是struts2上傳,fileUploadOther.action的是寫IO操作 -->    <!-- <form action="/struts2upload/system/upload/fileUpload.action" enctype="multipart/form-data" method="post">                請選擇檔案:<input type="file" id="fileOp" name="fileOp" /><input type="submit" value="上傳" />           </form>  -->    <br/><br/> <form action="/struts2upload/system/upload/fileUploadOther.action" enctype="multipart/form-data" method="post">                請選擇檔案:<input type="file" id="fileOp" name="fileOp" /><input type="submit" value="上傳" />           </form>  </body>
<!-- spring的配置,把路徑依賴注入到設定檔裡面,IO操作那種方式用的savePath --><bean id="myFileUploadAction" class="com.zyujie.action.UploadAction" scope="prototype"><property name="savePath" value="D:\webapp\apache-tomcat-6.0.10\webapps\struts2upload\upfiles" /></bean>
<struts><!-- 該屬性指定需要Struts2處理的請求尾碼,該屬性的預設值是action,即所有匹配*.action的請求都由Struts2處理。如果使用者需要指定多個請求尾碼,則多個尾碼之間以英文逗號(,)隔開。 --><constant name="struts.action.extension" value="action" /><!-- 設定瀏覽器是否緩衝靜態內容,預設值為true(生產環境下使用),開發階段最好關閉 --><constant name="struts.serve.static.browserCache" value="false" /><!-- 當struts的設定檔修改後,系統是否自動重新載入該檔案,預設值為false(生產環境下使用),開發階段最好開啟 --><constant name="struts.configuration.xml.reload" value="true" /><!-- 開發模式下使用,這樣可以列印出更詳細的錯誤資訊 --><constant name="struts.devMode" value="true" /><!-- 預設的視圖主題 --><constant name="struts.ui.theme" value="simple" /><!-- 整合spring,把struts給spring容器管理 --><constant name="struts.objectFactory" value="spring" /><!-- 解決亂碼 --><constant name="struts.i18n.encoding" value="UTF-8" /><!-- 指定允許上傳的檔案最大位元組數。預設值是2097152(2M) --><constant name="struts.multipart.maxSize" value="2097152"/><!-- 設定上傳檔案的臨時檔案夾,預設使用javax.servlet.context.tempdir --><constant name="struts.multipart.saveDir" value="E:/test" /><package name="syserror" extends="struts-default">    <global-results>        <result name="sql">/system_error.jsp</result>        <result name="invalidinput">/invalid_input.jsp</result>        <result name="naming">/system_error.jsp</result>        <result name="io">/system_error.jsp</result>        <result name="nullpointer">/system_error.jsp</result>    </global-results>        <global-exception-mappings>        <exception-mapping result="sql" exception="java.sql.SQLException"></exception-mapping>        <exception-mapping result="invalidinput" exception="cn.codeplus.exception.InvalidInputException"></exception-mapping>        <exception-mapping result="naming" exception="javax.naming.NamingException"></exception-mapping>    </global-exception-mappings>    </package><!-- Configuration for the default package. --><package name="upload" namespace="/system/upload" extends="struts-default"><action name="fileUpload" class="myFileUploadAction" method="fileUpload"><!-- <param name="fileOpFileName">12345.gif</param> --><result name="success" type="redirect">/ok.jsp</result><result name="io" type="redirect">/system_error.jsp</result>        <result name="nullpointer" type="redirect">/system_error.jsp</result><exception-mapping result="io" exception="java.io.IOException"></exception-mapping><exception-mapping result="nullpointer" exception="java.lang.NullPointerException"></exception-mapping></action>        <action name="fileUploadOther" class="myFileUploadAction" method="fileUploadOther">        <!-- 動態設定savePath的屬性值,設定為伺服器上的路徑 -->        <!-- <param name="savePath">D:\webapp\apache-tomcat-6.0.10\webapps\struts2upload\upfiles</param> -->        <param name="fileOpFileName">abcde.xls</param>        <result name="success" type="redirect">/ok.jsp</result>        <result name="input" type="redirect">/index.jsp</result>        <!-- 實現struts的預設攔截器功能,所以要在後面加一個defaultStack,預設攔截棧 -->        <interceptor-ref name="fileUpload">       <!-- 檔案過濾        <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param>-->        <!-- 檔案大小, 以位元組為單位 -->        <param name="maximumSize">2097152</param>        </interceptor-ref>        <!-- 預設攔截器必須放在fileUpload之後,否則無效 -->        <interceptor-ref name="defaultStack" />        </action>        </package></struts>
package com.zyujie.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class UploadAction extends ActionSupport {// 上傳的檔案private File fileOp;//檔案名稱 private String fileOpFileName;//檔案類型private String fileOpContentType;// 接受依賴注入的屬性    private String savePath;/* * 上傳檔案,把異常往外拋,聲明式異常處理,把異常交給struts的xml來進行配置處理,可見strut2的配置xml */public String fileUpload() throws IOException{//伺服器上的路徑String realpath = ServletActionContext.getServletContext().getRealPath("/upfiles");System.out.println("realpath: "+realpath);if (fileOp != null) {File savefile = new File(new File(realpath), fileOpFileName);if (!savefile.getParentFile().exists()){/**如果檔案夾不存在,就建立一個檔案夾**/savefile.getParentFile().mkdirs();}FileUtils.copyFile(fileOp, savefile);//調用struts2的上傳組件,進行檔案寫入//沒有拋異常,說明檔案上傳成功System.out.println("檔案上傳成功!");}return "success";}/* * 通過IO流去上傳檔案,採用手動處理異常,這樣不夠簡潔 */public String fileUploadOther(){FileOutputStream os = null;FileInputStream is = null;try {// 建立檔案輸出資料流System.out.println(getSavePath());os = new FileOutputStream(getSavePath() + "\\" + getFileOpFileName());// 建立檔案上傳流is = new FileInputStream(getFileOp());byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) > 0) {os.write(buffer, 0, len);}} catch (Exception e) {System.out.println("檔案上傳失敗");e.printStackTrace();} finally {close(os, is);}return "success";}/* * 關閉IO流 */private void close(FileOutputStream os, FileInputStream is) {if (is != null) {try {is.close();} catch (IOException e) {System.out.println("FileInputStream關閉失敗");e.printStackTrace();}}if (os != null) {try {os.close();} catch (IOException e) {System.out.println("FileOutputStream關閉失敗");e.printStackTrace();}}}public File getFileOp() {return fileOp;}public void setFileOp(File fileOp) {this.fileOp = fileOp;}public String getFileOpFileName() {return fileOpFileName;}public void setFileOpFileName(String fileOpFileName) {this.fileOpFileName = fileOpFileName;}public String getFileOpContentType() {return fileOpContentType;}public void setFileOpContentType(String fileOpContentType) {this.fileOpContentType = fileOpContentType;}public String getSavePath() {return savePath;}public void setSavePath(String savePath) {this.savePath = savePath;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.