Struts1檔案上傳、單檔案、多檔案上傳【Struts1】

來源:互聯網
上載者:User

標籤:

 將struts1檔案上傳的操作匯總了一下,包括單檔案上傳和多檔案上傳,內容如下,留作備忘:

 Struts2實現檔案上傳的文章(http://blog.csdn.net/itwit/article/details/7031785)

1、單檔案上傳

1)JSP頁面(singleFileUpload.jsp)

<%@page pageEncoding = "UTF-8"%><h1>檔案上傳</h1><hr /><form action="upload.action" method="post" enctype="multipart/form-data">name:<input type="text" name="name" /><br />upload:<input type="file" name="file" /><br /><input type="submit" value="上傳" /></form>

 

操作點:enctype="multipart/form-data"

2)Form(UploadForm)

package fileUpload.singleFileUpload.form;import org.apache.struts.action.ActionForm;import org.apache.struts.upload.FormFile;public class UploadForm extends ActionForm {private static final long serialVersionUID = 1L;private String name;private FormFile file;public String getName() {return name;}public void setName(String name) {this.name = name;}public FormFile getFile() {return file;}public void setFile(FormFile file) {this.file = file;}}

 操作點:Struts1提供了一個FormFile類來處理檔案上傳操作,另外注意,屬性name,file名字必須與jsp頁面一致,否則會報null 指標。

3)Action(UploadAction)

package fileUpload.singleFileUpload.action;import java.io.FileOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.upload.FormFile;import fileUpload.singleFileUpload.form.UploadForm;public class UploadAction extends Action {// @Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {   UploadForm uf = (UploadForm)form;   String name = uf.getName();   FormFile file = uf.getFile();   System.out.println("name=" + name);   String filename = file.getFileName();   System.out.println("fileName=" + filename);     FileOutputStream fos = new FileOutputStream("d:\\["+name+"]" + filename); //建立輸出資料流   fos.write(file.getFileData()); //寫入   fos.flush();//釋放   fos.close(); //關閉   return mapping.findForward("success"); }}

 操作點:FormFile類的方法

4)Struts設定檔(struts-config.xml)

<!-- 配置 單個上傳 --><form-bean name="uploadForm" type="fileUpload.singleFileUpload.form.UploadForm" />

 

<!-- 配置 單個上傳 --><action path="/upload" type="fileUpload.singleFileUpload.action.UploadAction" name="uploadForm" scope="request">    <forward name="success" path="/singleFileUpload.jsp" /></action>

 

<!-- 設定檔上傳大小 --><!-- 規定了最大上傳大小是2M,如果設定成-1則大小無限制了 --><controller maxFileSize="2M" />

 操作點:controller maxFileSize用來配置上傳檔案的大小,可根據實際情況配置,設定成-1則表示無限制。其位置必須放在</action-mappings>和<message-resources>之間

 

2、多檔案上傳

1)JSP頁面(mutityFileUpload.jsp)(從網上獲得的代碼,可增可減,不錯)

<%@ page pageEncoding="utf-8"%><%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%><html><head><title>上傳任意多個檔案(總大小不能超過2M)</title><script language="javascript">  // 在DOM中插入一個上傳檔案清單項(div元素)和一個<input type="file"/>元素  function insertNextFile(obj)   { // 擷取上傳控制個數      var childnum = document.getElementById("files").getElementsByTagName("input").length;             var id = childnum - 1;      var fullName = obj.value;      // 插入<div>元素及其子項目      var fileHtml = ‘‘;      fileHtml += ‘<div  id = "file_preview‘ + id + ‘" style ="border-bottom: 1px solid #CCC;">‘;      fileHtml += ‘<img  width =30 height = 30 src ="images/file.gif" title="‘ + fullName + ‘"/>‘;      fileHtml += ‘<a href="javascript:;" onclick="removeFile(‘ + id + ‘);">刪除</a>   ‘;      fileHtml += fullName.substr(fullName.lastIndexOf(‘\\‘)+1) +‘  </div>‘;        var fileElement = document.getElementById("files_preview");      fileElement.innerHTML = fileElement.innerHTML + fileHtml;          obj.style.display = ‘none‘;   // 隱藏當前的<input type=”file”/>元素      addUploadFile(childnum);  // 插入新的<input type=”file”/>元素  }  //  插入新的<input type=”file”/>元素,適合於不同的瀏覽器(包括IE、FireFox等)  function addUploadFile(index)  {      try  // 用於IE瀏覽器      {             var uploadHTML = document.createElement( "<input type=‘file‘ id=‘file_" + index +                                   "‘ name=‘file[" + index + "]‘ onchange=‘insertNextFile(this)‘/>");          document.getElementById("files").appendChild(uploadHTML);      }      catch(e)  // 用於其他瀏覽器      {           var uploadObj = document.createElement("input");          uploadObj.setAttribute("name", "file[" + index + "]");          uploadObj.setAttribute("onchange", "insertNextFile(this)");          uploadObj.setAttribute("type", "file");          uploadObj.setAttribute("id", "file_" + index);          document.getElementById("files").appendChild(uploadObj);      }  }  function removeFile(index)  // 刪除當前檔案的<div>和<input type=”file”/>元素  {      document.getElementById("files_preview").removeChild(document.getElementById("file_preview" + index));       document.getElementById("files").removeChild(document.getElementById("file_" + index));      }  function showStatus(obj)  // 顯示“正在上傳檔案”提示資訊  {    document.getElementById("status").style.visibility="visible";  }</script></head><body><html:form enctype="multipart/form-data" action="multiUpload"><span id="files"> <%--  在此處插入用於上傳檔案的input元素 --%>    <input type="file" id="file_0" name="file[0]" onchange="insertNextFile(this)" /> </span>                 <html:submit value=" 上傳 " onclick="showStatus(this);" /></html:form><p><div id="status" style="visibility: hidden; color: Red">正在上傳檔案</div><p><%--  在此處用DOM技術插入上傳檔案清單項  --%><div id="files_preview"style="width: 500px; height: 500px; overflow: auto"></div></body></html>

 2)Form(UploadMoreForm)

package fileUpload.mutityFileUpload.form;import java.util.ArrayList;import java.util.List;import org.apache.struts.action.ActionForm;import org.apache.struts.upload.FormFile;public class UploadMoreForm extends ActionForm{private static final long serialVersionUID = 1L;private List<FormFile> myFiles = new ArrayList<FormFile>();  // 用於儲存不定數量的FormFile對象      public FormFile getFile(int i)  // 索引屬性    {        return myFiles.get(i);    }    public void setFile(int i, FormFile myFile)  // 索引屬性    {        if (myFile.getFileSize() > 0)  // 只有上傳檔案的位元組數大於0,才上傳這個檔案        {            myFiles.add(myFile);        }    }    public int getFileCount()  // 獲得上傳檔案的個數    {        return myFiles.size();    }}

 3)Action(UploadMoreAction)

package fileUpload.mutityFileUpload.action;import java.io.FileOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.upload.FormFile;import fileUpload.mutityFileUpload.form.UploadMoreForm;public class UploadMoreAction extends Action {public ActionForward execute(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response)    {        UploadMoreForm umForm = (UploadMoreForm) form;        int count = 0;        try        {            count = umForm.getFileCount();   // 獲得上傳檔案的總數            for (int i = 0; i < count; i++)            {            FormFile file = umForm.getFile(i);             System.out.println(file.getFileName());            FileOutputStream fos = new FileOutputStream("d:\\" + file.getFileName()); //建立輸出資料流            fos.write(file.getFileData()); //寫入                fos.flush();//釋放            fos.close(); //關閉                        }        }        catch (Exception e)        {        e.printStackTrace();        }        return null;    }}

 4)Struts設定檔(struts-config.xml)

<!-- 配置 多個上傳 --><form-bean name="uploadMoreForm" type="fileUpload.mutityFileUpload.form.UploadMoreForm" />

 

<!-- 配置 多個上傳 --><action path="/multiUpload" type="fileUpload.mutityFileUpload.action.UploadMoreAction" name="uploadMoreForm" scope="request">    <forward name="success" path="/mutityFileUpload.jsp" /></action>

 

<!-- 設定檔上傳大小 --><!-- 規定了最大上傳大小是2M,如果設定成-1則大小無限制了 --><controller maxFileSize="-1" />

 

Struts1檔案上傳、單檔案、多檔案上傳【Struts1】

相關文章

聯繫我們

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