程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> struts2上傳多個文件,下載 配制!代碼

struts2上傳多個文件,下載 配制!代碼

編輯:關於JSP

頁面代碼:   注意,我在頁面在一個新建的文件夾下(TheNameSpace)     [html]  <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   <%@ taglib prefix="s" uri="/struts-tags" %>   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   <html>     <head>       <title>My JSP 'uplod.jsp' starting page</title>     </head>     <body>     <h1>file upload</h1>     <s:form action="uploadList.action" enctype="multipart/form-data" theme="simple">     <table cellpadding="0"  height="5" >       <tr>     <td>用戶:</td>     <td>     <s:textfield name="username"/>     </td>     </tr>          <tr>     <td>密碼:</td>    <td> <s:password name="passwrod"/></td>      </tr>      <tr >      <td>文件:</td>      <td id="fileID">      <s:fielderror name="file"/>     <s:file name="file" />     <a href="javascript:addFiles()" >添加上傳</a>     </td>     </tr>          <tr>     <td colspan="2">     <s:submit value="提交"/>     <s:reset value="重置"/>       </td>     </tr>      </table>     </s:form>     <script language="javascript">       function addFiles(){              var tdID=document.getElementById("fileID");              var br=document.createElement("br");       var file=document.createElement("input");       var button=document.createElement("input");                    file.type="file";       file.name="file";              button.type="button";       button.value="remove";       button.onclick=function(){       tdID.removeChild(br);       tdID.removeChild(file);       tdID.removeChild(button);       }                           tdID.appendChild(br);       tdID.appendChild(file);       tdID.appendChild(button);       }                  </script>     </body>   </html>     <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>   <head>     <title>My JSP 'uplod.jsp' starting page</title>   </head>   <body>   <h1>file upload</h1>   <s:form action="uploadList.action" enctype="multipart/form-data" theme="simple">   <table cellpadding="0"  height="5" >     <tr>   <td>用戶:</td>   <td>   <s:textfield name="username"/>   </td>   </tr>      <tr>   <td>密碼:</td>  <td> <s:password name="passwrod"/></td>    </tr>    <tr >    <td>文件:</td>    <td id="fileID">    <s:fielderror name="file"/>   <s:file name="file" />   <a href="javascript:addFiles()" >添加上傳</a>   </td>   </tr>      <tr>   <td colspan="2">   <s:submit value="提交"/>   <s:reset value="重置"/>     </td>   </tr>    </table>   </s:form>   <script language="javascript">     function addFiles(){          var tdID=document.getElementById("fileID");          var br=document.createElement("br");     var file=document.createElement("input");     var button=document.createElement("input");              file.type="file";     file.name="file";          button.type="button";     button.value="remove";     button.onclick=function(){     tdID.removeChild(br);     tdID.removeChild(file);     tdID.removeChild(button);     }                   tdID.appendChild(br);     tdID.appendChild(file);     tdID.appendChild(button);     }            </script>   </body> </html>   struts.xml配制文件:     [html]  <?xml version="1.0" encoding="UTF-8"?>    <!DOCTYPE struts PUBLIC       "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"       "http://struts.apache.org/dtds/struts-2.3.dtd">              <struts>       <!-- 常量 上傳文件 最大大小 -->       <constant name="struts.multipart.maxSize" value="20971520"/>              <!-- 包括這個xml -->       <include file="strtus_1.xml"/>              <!-- 後台action  -->       <package name="back" extends="struts-default" namespace="/TheNameSpace">              <action name="logins" class="com.rui.struts2.SpaceLogin">       <result name="success">showUser.jsp</result>       </action>              <action name="uploadList" class="com.rui.struts.UploadList">       <result name="success">ok.jsp</result>        <result name="input">/${pageContext.request.contextPath}/TheNameSpace/uploadList.jsp</result>              <!--攔截上上傳文件的 大小、格式  -->       <interceptor-ref name="fileUpload">       <param name="setAllowedTypes">image/pjpeg,image/gif,image/bmp,image/jpeg,image/jpg, text/plain, application/java-archive</param>       <param name="maximumSize">524288</param>       </interceptor-ref>        <interceptor-ref name="basicStack"/>       </action>              <action name="upload" class="com.rui.struts.Upload">       <result name="success">ok.jsp</result>       <result name="input">upload.jsp</result>       </action>              <action name="download" class="com.rui.struts.DownLoald">       <result  type="stream">       <!-- 要下載的文件        <param name="contentDisposition">attachment;filename="bbbb.txt"</param>       -->       <!-- 自動尋找方法 -->       <param name="inputName">downloadFile</param>       </result>              </action>       <action name="showlist" class="com.rui.struts.ShowFileList">       <result>download.jsp</result>       </action>              </package>                        </struts>     <?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">   <struts> <!-- 常量 上傳文件 最大大小 --> <constant name="struts.multipart.maxSize" value="20971520"/>   <!-- 包括這個xml --> <include file="strtus_1.xml"/>   <!-- 後台action  --> <package name="back" extends="struts-default" namespace="/TheNameSpace">   <action name="logins" class="com.rui.struts2.SpaceLogin"> <result name="success">showUser.jsp</result> </action>   <action name="uploadList" class="com.rui.struts.UploadList"> <result name="success">ok.jsp</result>  <result name="input">/${pageContext.request.contextPath}/TheNameSpace/uploadList.jsp</result>   <!--攔截上上傳文件的 大小、格式  --> <interceptor-ref name="fileUpload"> <param name="setAllowedTypes">image/pjpeg,image/gif,image/bmp,image/jpeg,image/jpg, text/plain, application/java-archive</param> <param name="maximumSize">524288</param> </interceptor-ref>      <interceptor-ref name="basicStack"/> </action>   <action name="upload" class="com.rui.struts.Upload"> <result name="success">ok.jsp</result> <result name="input">upload.jsp</result> </action>   <action name="download" class="com.rui.struts.DownLoald"> <result  type="stream"> <!-- 要下載的文件  <param name="contentDisposition">attachment;filename="bbbb.txt"</param> --> <!-- 自動尋找方法 --> <param name="inputName">downloadFile</param> </result>   </action> <action name="showlist" class="com.rui.struts.ShowFileList"> <result>download.jsp</result> </action>   </package>       </struts>   action 上傳類的代碼:     [html] package com.rui.struts;      import java.io.File;   import java.io.FileInputStream;   import java.io.FileOutputStream;   import java.io.InputStream;   import java.io.OutputStream;   import java.util.List;      import org.apache.struts2.ServletActionContext;      import com.opensymphony.xwork2.ActionSupport;      public class UploadList extends ActionSupport {       private String username;       private String passwrod;       private List<File> file;       private List<String> fileFileName;       private List<String> fileContentType;                            public String getUsername() {           return username;       }       public void setUsername(String username) {           this.username = username;       }       public String getPasswrod() {           return passwrod;       }       public void setPasswrod(String passwrod) {           this.passwrod = passwrod;       }       public List<File> getFile() {           return file;       }       public void setFile(List<File> file) {           this.file = file;       }       public List<String> getFileFileName() {           return fileFileName;       }       public void setFileFileName(List<String> fileFileName) {           this.fileFileName = fileFileName;       }       public List<String> getFileContentType() {           return fileContentType;       }       public void setFileContentType(List<String> fileContentType) {           this.fileContentType = fileContentType;       }              @Override       public void validate() {           System.out.println("執行了驗證器...");           if(null==file){               addFieldError("file", "請選擇文件!");           }       }                     @Override       public String execute() throws Exception {           if(null==file||file.size()<=0){               addFieldError("file", "請上傳符合格式的文件....");               return INPUT;           }       //獲得路麼       String path=ServletActionContext.getRequest().getRealPath("upload");              for(int i=0;i<file.size();i++){       //輸入流       InputStream is=new FileInputStream(file.get(i));              //File 對象       File fileObj=new File(path,fileFileName.get(i));               //輸出流       OutputStream os=new FileOutputStream(fileObj);              byte [] by=new byte[400];       int length=0;       while(-1!=(length=is.read(by))){           os.write(by,0,length);       }              os.close();       is.close();                      }                         return SUCCESS;       }             }     package com.rui.struts;   import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.List;   import org.apache.struts2.ServletActionContext;   import com.opensymphony.xwork2.ActionSupport;   public class UploadList extends ActionSupport { private String username; private String passwrod; private List<File> file; private List<String> fileFileName; private List<String> fileContentType;       public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPasswrod() { return passwrod; } public void setPasswrod(String passwrod) { this.passwrod = passwrod; } public List<File> getFile() { return file; } public void setFile(List<File> file) { this.file = file; } public List<String> getFileFileName() { return fileFileName; } public void setFileFileName(List<String> fileFileName) { this.fileFileName = fileFileName; } public List<String> getFileContentType() { return fileContentType; } public void setFileContentType(List<String> fileContentType) { this.fileContentType = fileContentType; }   @Override public void validate() { System.out.println("執行了驗證器..."); if(null==file){ addFieldError("file", "請選擇文件!"); } }     @Override public String execute() throws Exception { if(null==file||file.size()<=0){ addFieldError("file", "請上傳符合格式的文件...."); return INPUT; } //獲得路麼 String path=ServletActionContext.getRequest().getRealPath("upload");   for(int i=0;i<file.size();i++){ //輸入流 InputStream is=new FileInputStream(file.get(i));   //File 對象 File fileObj=new File(path,fileFileName.get(i));    //輸出流 OutputStream os=new FileOutputStream(fileObj);   byte [] by=new byte[400]; int length=0; while(-1!=(length=is.read(by))){ os.write(by,0,length); }   os.close(); is.close();   }     return SUCCESS; }     }         下載頁面測試 :     [html] <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   <%@ taglib prefix="s" uri="/struts-tags" %>   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   <html>     <head>       <title>My JSP 'download.jsp' starting page</title>     </head>     <body>          <s:iterator value="listName" var="lname">     <s:property value="lname"/><br/><br/>      <a href="download.action?lname=<s:property value='#lname'/>" >下載文件<a>     <!--     <a href="download.action?lname=DWHJ_062001.jpg">下載文件</a>     -->     </s:iterator>          <br/><br/>               </body>   </html>     <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>   <head>     <title>My JSP 'download.jsp' starting page</title>   </head>   <body>      <s:iterator value="listName" var="lname">   <s:property value="lname"/><br/><br/>    <a href="download.action?lname=<s:property value='#lname'/>" >下載文件<a>   <!--    <a href="download.action?lname=DWHJ_062001.jpg">下載文件</a>    -->   </s:iterator>      <br/><br/>         </body> </html>               action 下載代碼:    [html]  package com.rui.struts;      import java.io.InputStream;   import java.io.UnsupportedEncodingException;      import javax.servlet.http.HttpServletRequest;   import javax.servlet.http.HttpServletResponse;      import org.apache.struts2.ServletActionContext;      import com.opensymphony.xwork2.ActionSupport;      public class DownLoald extends ActionSupport {              private String lname;              public String getLname() {           return lname;       }             public void setLname(String lname) {           this.lname = lname;       }          private String slname="" ;              public InputStream getDownloadFile(){              HttpServletResponse response=ServletActionContext.getResponse();       try {           slname=new String(lname.getBytes("ISO-8859-1"),"UTF-8");       } catch (UnsupportedEncodingException e1) {           // TODO Auto-generated catch block           e1.printStackTrace();       }                            try {           lname=java.net.URLEncoder.encode(slname,"utf-8");       } catch (UnsupportedEncodingException e) {           // TODO Auto-generated catch block           e.printStackTrace();       }                       System.out.println("ddd"+lname);       response.setHeader("Content-Disposition","attachment;filename="+lname);                      return ServletActionContext.getServletContext().           getResourceAsStream("upload/"+slname);       }                 //文件名如果有中文的話要進行uri中文轉碼               /*String encodFileNmae="";               try {                    encodFileNmae=java.net.URLEncoder.encode(u.getOldname(),"utf-8");               } catch (UnsupportedEncodingException e1) {                   // TODO Auto-generated catch block                   e1.printStackTrace();               }                              //設置一個請求頭告訴浏覽器有文件要下載               response.setContentType("text/html;charset=utf-8");                    response.setHeader("Content-Disposition","attachment;filename="+encodFileNmae);       */                     @Override       public String execute() throws Exception {                      return SUCCESS;       }      }     package com.rui.struts;   import java.io.InputStream; import java.io.UnsupportedEncodingException;   import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   import org.apache.struts2.ServletActionContext;   import com.opensymphony.xwork2.ActionSupport;   public class DownLoald extends ActionSupport {   private String lname;   public String getLname() { return lname; }     public void setLname(String lname) { this.lname = lname; }   private String slname="" ;   public InputStream getDownloadFile(){   HttpServletResponse response=ServletActionContext.getResponse(); try { slname=new String(lname.getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }       try { lname=java.net.URLEncoder.encode(slname,"utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); }     System.out.println("ddd"+lname); response.setHeader("Content-Disposition","attachment;filename="+lname);   return ServletActionContext.getServletContext(). getResourceAsStream("upload/"+slname); }     //文件名如果有中文的話要進行uri中文轉碼 /*String encodFileNmae=""; try { encodFileNmae=java.net.URLEncoder.encode(u.getOldname(),"utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }   //設置一個請求頭告訴浏覽器有文件要下載 response.setContentType("text/html;charset=utf-8"); response.setHeader("Content-Disposition","attachment;filename="+encodFileNmae); */     @Override public String execute() throws Exception {   return SUCCESS; }   }
\

 

\\\


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved