Struts2 文件上傳,下載,刪除

本文介紹了:
1.基於表單的文件上傳
2.Struts 2 的文件下載
3.Struts2.文件上傳
4.使用FileInputStream FileOutputStream文件流來上傳
5.使用FileUtil上傳
6.使用IOUtil上傳
7.使用IOUtil上傳
8.使用數組上傳多個文件
9.使用List上傳多個文件 css

----1.基於表單的文件上傳-----java

fileupload.jspweb

    <body>  
        <form action="showFile.jsp" name="myForm" method="post" enctype="multipart/form-data">  
            選擇上傳的文件   
            <input type="file" name="myfile"><br/><br/>  
            <input type="submit" name="mySubmit" value="上傳"/>    
        </form>  
     </body>  

showFile.jspapache

    <body>  
         上傳的文件的內容以下:   
         <%   
         InputStream is=request.getInputStream();   
         InputStreamReader isr=new InputStreamReader(is);   
         BufferedReader br=new BufferedReader(isr);   
         String content=null;   
         while((content=br.readLine())!=null){   
             out.print(content+"<br/>");   
         }   
         %>  
      </body>  

----2.手動上傳-----數組

  1. 經過二進制劉獲取上傳文件的內容,並將上傳的文件內容保存到服務器的某個目錄,這樣就實現了文件上傳。因爲這個處理過程徹底依賴與開發本身處理二進制流,因此也稱爲「手動上傳」。   
  2. 從上面的第一個例子能夠看到,使用二進制流獲取的上傳文件的內容與實際文件的內容有仍是有必定的區別,包含了不少實際文本中沒有的字符。因此須要對獲取的內容進行解析,去掉額外的字符。

----3 Struts2.文件上傳----服務器

  1. Struts2中使用Common-fileUpload文件上傳框架,須要在web應用中增長兩個Jar 文件, 即 commons-fileupload.jar. commons-io.jar   
  2. 須要使用fileUpload攔截器:具體的說明在 struts2-core-2.3.4.jar \org.apache.struts2.interceptor\FileUploadInterceptor.class 裏面    
  3. 下面來看看一點源代碼 
    public class FileUploadInterceptor extends AbstractInterceptor {   
      
        private static final long serialVersionUID = -4764627478894962478L;   
      
        protected static final Logger LOG = LoggerFactory.getLogger(FileUploadInterceptor.class);   
        private static final String DEFAULT_MESSAGE = "no.message.found";   
      
        protected boolean useActionMessageBundle;   
      
        protected Long maximumSize;   
        protected Set<String> allowedTypesSet = Collections.emptySet();   
        protected Set<String> allowedExtensionsSet = Collections.emptySet();   
      
        private PatternMatcher matcher;   
      
     @Inject  
        public void setMatcher(PatternMatcher matcher) {   
            this.matcher = matcher;   
        }   
      
        public void setUseActionMessageBundle(String value) {   
            this.useActionMessageBundle = Boolean.valueOf(value);   
        }   
      
        //這就是struts.xml 中param爲何要配置爲 allowedExtensions   
        public void setAllowedExtensions(String allowedExtensions) {   
            allowedExtensionsSet = TextParseUtil.commaDelimitedStringToSet(allowedExtensions);   
        }   
        //這就是struts.xml 中param爲何要配置爲 allowedTypes 而不是 上面的allowedTypesSet    
        public void setAllowedTypes(String allowedTypes) {   
            allowedTypesSet = TextParseUtil.commaDelimitedStringToSet(allowedTypes);   
        }   
      
        public void setMaximumSize(Long maximumSize) {   
            this.maximumSize = maximumSize;   
        }   
    }  
官員文件初始值大小 上面的類中的說明   
<li>maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be set   
 * on the action. Note, this is <b>not</b> related to the various properties found in struts.properties.   
 * Default to approximately 2MB.</li>  
具體說的是這個值在struts.properties 中有設置。 下面就來看 裏面的設置   
  
### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data   
  
文件上傳解析器     
# struts.multipart.parser=cos  
# struts.multipart.parser=pell  
#默認 使用jakata框架上傳文件   
struts.multipart.parser=jakarta  
  
#上傳時候 默認的臨時文件目錄     
# uses javax.servlet.context.tempdir by default   
struts.multipart.saveDir=   
  
#上傳時候默認的大小   
struts.multipart.maxSize=2097152

案例:使用FileInputStream FileOutputStream文件流來上傳 app

action.java框架

    package com.sh.action;   
      
    import java.io.File;   
    import java.io.FileInputStream;   
    import java.io.FileOutputStream;   
      
    import org.apache.struts2.ServletActionContext;   
      
    import com.opensymphony.xwork2.ActionSupport;   
      
    public class MyUpAction extends ActionSupport {   
           
        private File upload; //上傳的文件   
        private String uploadContentType; //文件的類型   
        private String uploadFileName; //文件名稱   
        private String savePath; //文件上傳的路徑   
           
    //注意這裏的保存路徑   
        public String getSavePath() {   
            return ServletActionContext.getRequest().getRealPath(savePath);   
        }   
        public void setSavePath(String savePath) {   
            this.savePath = savePath;   
        }   
        @Override  
        public String execute() throws Exception {   
            System.out.println("type:"+this.uploadContentType);   
            String fileName=getSavePath()+"\\"+getUploadFileName();   
            FileOutputStream fos=new FileOutputStream(fileName);   
            FileInputStream fis=new FileInputStream(getUpload());   
            byte[] b=new byte[1024];   
            int len=0;   
            while ((len=fis.read(b))>0) {   
                fos.write(b,0,len);   
            }   
            fos.flush();   
            fos.close();   
            fis.close();   
            return SUCCESS;   
        }   
    //get set   
    }  

struts.xmldom

 

    <?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.i18n.encoding" value="utf-8"/>  
        <constant name="struts.devMode" value="true"/>     
        <constant name="struts.convention.classes.reload" value="true" />    
           
        <constant name="struts.multipart.saveDir" value="f:/tmp"/>  
        <package name="/user" extends="struts-default">  
            <action name="up" class="com.sh.action.MyUpAction">  
                <result name="input">/up.jsp</result>  
                <result name="success">/success.jsp</result>  
                <!-- 在web-root目錄下新建的一個 upload目錄 用於保存上傳的文件 -->  
                <param name="savePath">/upload</param>  
                <interceptor-ref name="fileUpload">  
                    <!--採用設置文件的類型 來限制上傳文件的類型-->  
                    <param name="allowedTypes">text/plain</param>  
                    <!--採用設置文件的後綴來限制上傳文件的類型 -->  
                    <param name="allowedExtensions">png,txt</param>  
                    <!--設置文件的大小 默認爲 2M [單位:byte] -->  
                    <param name="maximumSize">1024000</param>  
                </interceptor-ref>               
                           
                <interceptor-ref name="defaultStack"/>  
            </action>  
        </package>  
    </struts>  

 

up.jspjsp

 

    <body>  
      <h2>Struts2 上傳文件</h2>  
       <s:fielderror/>  
      <s:form action="up" method="post" name="upform" id="form1" enctype="multipart/form-data" theme="simple">  
            選擇文件:   
           <s:file name="upload" cssStyle="width:300px;"/>  
           <s:submit value="肯定"/>  
      </s:form>         
    </body>  

 

success.jsp

 

    <body>  
      <b>上傳成功!</b>  
      <s:property value="uploadFileName"/><br/>  
      [img]<s:property value="'upload/'+uploadFileName"/>[/img]   
    </body>  

 

案例:使用FileUtil上傳

action.java

 

    package com.sh.action;   
      
    import java.io.File;   
    import java.io.IOException;   
    import java.text.DateFormat;   
    import java.text.SimpleDateFormat;   
    import java.util.Date;   
    import java.util.Random;   
    import java.util.UUID;   
      
    import org.apache.commons.io.FileUtils;   
    import org.apache.struts2.ServletActionContext;   
      
    import com.opensymphony.xwork2.ActionContext;   
    import com.opensymphony.xwork2.ActionSupport;   
      
    public class FileUtilUpload extends ActionSupport {   
        private File image; //文件   
        private String imageFileName; //文件名   
        private String imageContentType;//文件類型   
        public String execute(){   
            try {   
                if(image!=null){   
                    //文件保存的父目錄   
                    String realPath=ServletActionContext.getServletContext()   
                    .getRealPath("/image");   
                    //要保存的新的文件名稱   
                    String targetFileName=generateFileName(imageFileName);   
                    //利用父子目錄穿件文件目錄   
                    File savefile=new File(new File(realPath),targetFileName);   
                    if(!savefile.getParentFile().exists()){   
                        savefile.getParentFile().mkdirs();   
                    }   
                    FileUtils.copyFile(image, savefile);   
                    ActionContext.getContext().put("message", "上傳成功!");   
                    ActionContext.getContext().put("filePath", targetFileName);   
                }   
            } catch (IOException e) {   
                // TODO Auto-generated catch block   
                e.printStackTrace();   
            }   
            return "success";   
        }   
           
        /**  
         * new文件名= 時間 + 隨機數  
         * @param fileName: old文件名  
         * @return new文件名  
         */  
        private String generateFileName(String fileName) {   
            //時間   
            DateFormat df = new SimpleDateFormat("yyMMddHHmmss");      
            String formatDate = df.format(new Date());   
            //隨機數   
            int random = new Random().nextInt(10000);    
            //文件後綴   
            int position = fileName.lastIndexOf(".");      
            String extension = fileName.substring(position);      
            return formatDate + random + extension;      
        }   
    //get set   
      
    }  

 

struts.xml

 

    <action name="fileUtilUpload" class="com.sh.action.FileUtilUpload">  
        <result name="input">/fileutilupload.jsp</result>  
        <result name="success">/fuuSuccess.jsp</result>  
    </action>  

 

fileutilupload.jsp

 

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

 

fuuSuccess.jsp

 

    <body>  
        <b>${message}</b>  
            ${imageFileName}<br/>  
        <img src="upload/${filePath}"/>  
      </body>  

 

案例:使用IOUtil上傳

action.java

    package com.sh.action;   
      
    import java.io.File;   
    import java.io.FileInputStream;   
    import java.io.FileOutputStream;   
    import java.text.DateFormat;   
    import java.text.SimpleDateFormat;   
    import java.util.Date;   
    import java.util.UUID;   
      
    import org.apache.commons.io.IOUtils;   
    import org.apache.struts2.ServletActionContext;   
      
    import com.opensymphony.xwork2.ActionContext;   
    import com.opensymphony.xwork2.ActionSupport;   
      
    public class IOUtilUpload extends ActionSupport {   
      
        private File image; //文件   
        private String imageFileName; //文件名   
        private String imageContentType;//文件類型   
        public String execute(){   
            try {     
               if(image!=null){   
                    //文件保存的父目錄   
                    String realPath=ServletActionContext.getServletContext()   
                    .getRealPath("/image");   
                    //要保存的新的文件名稱   
                    String targetFileName=generateFileName(imageFileName);   
                    //利用父子目錄穿件文件目錄   
                    File savefile=new File(new File(realPath),targetFileName);   
                    if(!savefile.getParentFile().exists()){   
                        savefile.getParentFile().mkdirs();   
                    }   
                    FileOutputStream fos=new FileOutputStream(savefile);   
                    FileInputStream fis=new FileInputStream(image);   
                       
                    //若是複製文件的時候 出錯了返回 值就是 -1 因此 初始化爲 -2   
                    Long result=-2L;   //大文件的上傳   
                    int  smresult=-2; //小文件的上傳   
                       
                    //若是文件大於 2GB   
                    if(image.length()>1024*2*1024){   
                        result=IOUtils.copyLarge(fis, fos);   
                    }else{   
                        smresult=IOUtils.copy(fis, fos);    
                    }   
                    if(result >-1 || smresult>-1){   
                        ActionContext.getContext().put("message", "上傳成功!");   
                    }   
                    ActionContext.getContext().put("filePath", targetFileName);   
               }   
            } catch (Exception e) {     
                e.printStackTrace();     
            }     
            return SUCCESS;     
        }   
           
        /**  
         * new文件名= 時間 + 全球惟一編號  
         * @param fileName old文件名  
         * @return new文件名  
         */  
        private String generateFileName(String fileName) {   
            //時間   
            DateFormat df = new SimpleDateFormat("yy_MM_dd_HH_mm_ss");      
            String formatDate = df.format(new Date());   
            //全球惟一編號   
            String uuid=UUID.randomUUID().toString();   
            int position = fileName.lastIndexOf(".");      
            String extension = fileName.substring(position);      
            return formatDate + uuid + extension;      
        }   
    //get set   
    }  

struts.xml

 

    <action name="iOUtilUpload" class="com.sh.action.IOUtilUpload">  
                <result name="input">/ioutilupload.jsp</result>  
                <result name="success">/iuuSuccess.jsp</result>  
    </action>  

 

ioutilupload.jsp

 

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

 

iuuSuccess.jsp

 

    <body>  
        <b>${message}</b>  
            ${imageFileName}<br/>  
        <img src="image/${filePath}"/>  
    </body>  

 

案例:刪除服務器上的文件

 

    /**  
         * 從服務器上 刪除文件  
         * @param fileName 文件名  
         * @return true: 從服務器上刪除成功   false:不然失敗  
         */  
        public boolean delFile(String fileName){   
            File file=new File(fileName);   
            if(file.exists()){   
                return file.delete();   
            }   
            return false;   
        }  

 

案例:使用數組上傳多個文件

action.java

 

    package com.sh.action;   
      
    import java.io.File;   
    import java.io.FileInputStream;   
    import java.io.FileOutputStream;   
    import java.util.Random;   
      
    import org.apache.struts2.ServletActionContext;   
      
    import com.opensymphony.xwork2.ActionContext;   
    import com.opensymphony.xwork2.ActionSupport;   
      
    /**  
     * @author Administrator  
     *  
     */  
    public class ArrayUpload extends ActionSupport {   
      
        private File[] image;   
        private String[] imageContentType;   
        private String[] imageFileName;   
        private String path;   
           
        public String getPath() {   
            return ServletActionContext.getRequest().getRealPath(path);   
        }   
      
        public void setPath(String path) {   
            this.path = path;   
        }   
      
        @Override  
        public String execute() throws Exception {   
          for(int i=0;i<image.length;i++){   
              imageFileName[i]=getFileName(imageFileName[i]);   
              String targetFileName=getPath()+"\\"+imageFileName[i];   
              FileOutputStream fos=new FileOutputStream(targetFileName);   
              FileInputStream fis=new FileInputStream(image[i]);   
              byte[] b=new byte[1024];   
              int len=0;   
              while ((len=fis.read(b))>0) {   
                fos.write(b, 0, len);   
            }   
          }   
          return SUCCESS;   
        }   
        private String getFileName(String fileName){   
            int position=fileName.lastIndexOf(".");   
            String extension=fileName.substring(position);   
            int radom=new Random().nextInt(1000);   
            return ""+System.currentTimeMillis()+radom+extension;   
        }   
    //get set   
    }  

 

struts.xml

    <action name="arrayUpload" class="com.sh.action.ArrayUpload">  
            <interceptor-ref name="fileUpload">  
                <param name="allowedTypes">  
                    image/x-png,image/gif,image/bmp,image/jpeg   
                </param>  
                <param name="maximumSize">10240000</param>  
            </interceptor-ref>  
            <interceptor-ref name="defaultStack"/>  
            <param name="path">/image</param>  
            <result name="success">/arraySuccess.jsp</result>  
            <result name="input">/arrayupload.jsp</result>  
        </action>  

arrayUpload.jsp

    <body>  
       ===========多文件上傳=================   
        <form action="${pageContext.request.contextPath }/arrayUpload.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"/>  
        <input type="submit" value="上傳"/>  
       </form>  
     </body>  

arraySuccess.jsp

    <body>  
        <b>使用數組上傳成功s:iterator</b>  
        <s:iterator value="imageFileName" status="st"><s:property value="#st.getIndex()+1"/>個圖片:<br/>  
            [img]image/<s:property value="imageFileName[#st.getIndex()][/img]"/>  
        </s:iterator>  
         <br/><b>使用數組上傳成功c:foreach</b>  
         <c:forEach var="fn" items="${imageFileName}" varStatus="st">  
            第${st.index+1}個圖片:<br/>  
            <img src="image/${fn}"/>  
         </c:forEach>  
      </body>  

案例:使用List上傳多個文件

action.java

 

    package com.sh.action;   
      
    import java.io.File;   
    import java.io.FileInputStream;   
    import java.io.FileOutputStream;   
    import java.util.List;   
    import java.util.Random;   
      
    import javax.servlet.Servlet;   
      
    import org.apache.struts2.ServletActionContext;   
      
    import com.opensymphony.xwork2.ActionSupport;   
      
    public class ListUpload extends ActionSupport {   
    private List<File> doc;   
    private List<String> docContentType;   
    private List<String> docFileName;   
    private String path;   
    @Override  
    public String execute() throws Exception {   
        for(int i=0;i<doc.size();i++){   
            docFileName.set(i, getFileName(docFileName.get(i)));   
            FileOutputStream fos=new FileOutputStream(getPath()+"\\"+docFileName.get(i));   
            File file=doc.get(i);   
            FileInputStream fis=new FileInputStream(file);   
            byte [] b=new byte[1024];   
            int length=0;   
            while((length=fis.read(b))>0){   
                fos.write(b,0,length);   
            }   
        }   
        return SUCCESS;   
    }   
      
      
    public String getFileName(String fileName){   
        int position=fileName.lastIndexOf(".");   
        String extension=fileName.substring(position);   
        int radom=new Random().nextInt(1000);   
        return ""+System.currentTimeMillis()+radom+extension;   
    }   
    public String getPath() {   
        return ServletActionContext.getRequest().getRealPath(path);   
    }  

 

strust.xml

    <action name="listUpload" class="com.sh.action.ListUpload">  
                <interceptor-ref name="fileUpload">  
                    <param name="allowedTypes">  
                        image/x-png,image/gif,image/bmp,image/jpeg   
                    </param>  
                    <param name="maximumSize">  
                        10240000   
                    </param>  
                </interceptor-ref>  
                <interceptor-ref name="defaultStack"/>  
                <param name="path">/image</param>  
                <result name="success">/listSuccess.jsp</result>  
                <result name="input">/listupload.jsp</result>  
            </action>  

listUpload.jsp

    <body>  
        ===========List 多文件上傳=================   
         <form action="${pageContext.request.contextPath }/listUpload.action"    
        enctype="multipart/form-data" method="post">  
            文件1:<input type="file" name="doc"/><br/>  
            文件2:<input type="file" name="doc"/><br/>  
            文件3:<input type="file" name="doc"/>  
            <input type="submit" value="上傳"/>  
        </form>  
          
         <s:fielderror/>  
        <s:form action="listUpload" enctype="multipart/form-data">  
        <s:file name="doc" label="選擇上傳的文件"/>  
            <s:file name="doc" label="選擇上傳的文件"/>  
            <s:file name="doc" label="選擇上傳的文件"/>  
            <s:submit value="上傳"/>  
        </s:form>  
            
      </body>  

listSuccess.jsp

    <body>  
        <h3>使用List上傳多個文件 s:iterator顯示</h3>  
        <s:iterator value="docFileName" status="st"><s:property value="#st.getIndex()+1"/>個圖片:   
            <br/>  
            <img src="image/<s:property value="docFileName.get(#st.getIndex())"/>"/><br/>  
        </s:iterator>  
        <h3>使用List上傳多個文件 c:foreach顯示</h3>  
        <c:forEach var="fn" items="${docFileName}" varStatus="st">  
              第${st.index}個圖片<br/>  
             <img src="image/${fn}"/>  
        </c:forEach>  
    </body>  

案例:Struts2 文件下載

Struts2支持文件下載,經過提供的stram結果類型來實現。指定stream結果類型是,還須要指定inputName參數,此參數表示輸入流,做爲文件下載入口。 

簡單文件下載 不含中文附件名

    package com.sh.action;   
      
    import java.io.InputStream;   
      
    import org.apache.struts2.ServletActionContext;   
      
    import com.opensymphony.xwork2.ActionSupport;   
      
    public class MyDownload extends ActionSupport {   
      
        private String inputPath;   
      
        //注意這的  方法名 在struts.xml中要使用到的   
        public InputStream getTargetFile() {   
            System.out.println(inputPath);   
            return ServletActionContext.getServletContext().getResourceAsStream(inputPath);   
        }   
           
        public void setInputPath(String inputPath) {   
            this.inputPath = inputPath;   
        }   
      
        @Override  
        public String execute() throws Exception {   
            // TODO Auto-generated method stub   
            return SUCCESS;   
        }   
           
           
    }  

Struts.xml

    <action name="mydownload" class="com.sh.action.MyDownload">  
                <!--給action中的屬性賦初始值-->  
            <param name="inputPath">/image/1347372060765110.jpg</param>  
    <!--給注意放回後的 type類型-->  
            <result name="success" type="stream">  
                          <!--要下載文件的類型-->  
                <param name="contentType">image/jpeg</param>  
                            <!--action文件輸入流的方法 getTargetFile()-->  
                <param name="inputName">targetFile</param>  
                            <!--文件下載的處理方式 包括內聯(inline)和附件(attachment)兩種方式--->  
                <param name="contentDisposition">attachment;filename="1347372060765110.jpg"</param>  
                           <!---下載緩衝區的大小-->  
                <param name="bufferSize">2048</param>  
            </result>  
        </action>  

down.jsp

    <body>  
            <h3>Struts 2 的文件下載</h3> <br>  
            <a href="mydownload.action">我要下載</a>  
    </body>  

文件下載,支持中文附件名 

action

 

    package com.sh.action;   
      
    import java.io.InputStream;   
      
    import org.apache.struts2.ServletActionContext;   
      
    import com.opensymphony.xwork2.ActionSupport;   
      
    public class DownLoadAction extends ActionSupport {   
      
        private final String DOWNLOADPATH="/image/";   
        private String fileName;   
             
            //這個方法 也得注意 struts.xml中也會用到   
        public InputStream getDownLoadFile(){   
            return ServletActionContext.getServletContext().getResourceAsStream(DOWNLOADPATH+fileName);   
        }   
        //轉換文件名的方法 在strust.xml中會用到   
        public String getDownLoadChineseFileName(){   
            String chineseFileName=fileName;   
            try {   
                chineseFileName=new String(chineseFileName.getBytes(),"ISO-8859-1");   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
            return chineseFileName;   
        }   
        @Override  
        public String execute() throws Exception {   
            // TODO Auto-generated method stub   
            return SUCCESS;   
        }   
      
        public String getFileName() {   
            return fileName;   
        }   
      
        public void setFileName(String fileName) {   
            this.fileName = fileName;   
        }   
           
    }  

 

struts.xml

    <action name="download" class="com.sh.action.DownLoadAction">  
                <param name="fileName">活動主題.jpg</param>  
                <result name="success" type="stream">  
                    <param name="contentType">image/jpeg</param>  
                            <!-- getDownLoadFile() 這個方法--->  
                    <param name="inputName">downLoadFile</param>  
                    <param name="contentDisposition">attachment;filename="${downLoadChineseFileName}"</param>  
                    <param name="bufferSize">2048</param>  
                </result>  
     </action>  

down1.jsp

    <body>  
            <h3>Struts 2 的文件下載</h3> <br>  
            <a href="download.action">我要下載</a>  
      </body>  
相關文章
相關標籤/搜索