Struts1.3——檔案上傳和下載

來源:互聯網
上載者:User

標籤:

1.Struts檔案上傳

在Web開發中,會經常涉及到檔案的上傳和下載,比如在註冊賬戶的時候,我們需要上傳自己的頭像等。
我們可以利用Struts很方便地實現檔案的上傳。

1.1 開發步驟

現在,假設我們要在註冊的時候上傳自己的頭像。建立項目名稱為StrutsFileUpAndDown,並引入Struts1.3

(1)首先,寫註冊的JSP頁面register.jsp
它的body內容如下:

<body>    <h1>註冊使用者</h1>    <% --如果表單有檔案控制項,則需要重新指定表單的編碼方式 --%>    <form enctype="multipart/form-data" action="/StrutsFileUpAndDown/register.do" method="post">        名字:<input type="text" name="name" /><br>         頭像:<input type="file" name="photo" /><br>         <input type="submit" value="註冊" />    </form></body>
  • 這裡使用普通的HTML標籤來寫表單。一定要注意加上form的enctype屬性,並且內容為”multipart/form-data”
  • 這裡必須使用post方法提交,get方法會出錯
  • action的地址剛開始的時候可以先空著,後面有了Action之後,再補上去。這裡我的Action的path為”/register”

(2)添加對應的ActionForm,名字為UserForm

public class UserForm extends ActionForm {    private String name = null;    private FormFile photo = null;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public FormFile getPhoto() {        return photo;    }    public void setPhoto(FormFile photo) {        this.photo = photo;    }}
  • 要知道的是,JSP中的檔案控制項對應的是FormFile對象,該對象由Struts架構提供。

(2)添加對應的Action,名字為RegisterAction,並配置path為/register
最關鍵的地方就在於Action是怎麼寫的,我們點擊註冊之後,是由Action來處理這個邏輯的,檔案也就是通過這個Action傳上來的。

  • 首先我們要得到UserForm中的內容:
UserForm userForm = (UserForm) form;String username = userForm.getName();FormFile formFile = userForm.getPhoto();
  • 接著,我們儲存檔案,FormFile對象有getInputStream()方法可以得到檔案的輸入資料流。此時我們還需要一個輸出資料流OutputStream,用於將輸入資料流拿到的東西通過輸出資料流儲存到伺服器的磁碟。但要注意輸出資料流的輸出路徑是Tomcat下的絕對路徑
// 檔案名稱String fileName = formFile.getFileName();// 擷取輸入資料流InputStream is = formFile.getInputStream();// 得到一個輸出資料流// 首先得到file檔案夾上傳到Tomcat伺服器後的絕對路徑String path = request.getServletContext().getRealPath("file");OutputStream os = new FileOutputStream(path + "\\" + fileName);// 讀取檔案並寫出到伺服器file檔案夾下int len = 0;// 做一個緩衝byte[] bytes = new byte[1024];// 迴圈處理while ((len = is.read(bytes)) > 0) {    // 讀一點,寫一點    os.write(bytes, 0, len);}

當然,這整個過程要處理異常。如果不出錯的話,我們就可以將檔案上傳給伺服器了。

【注意,這裡省略一些簡單的配置步驟】

1.2 改進

(1)問題1:中文亂碼的處理,如果使用者上傳的檔案是中文名稱會出現亂碼

此時,過濾器可以很好地解決這個問題。只需要加上一個過濾器,將request的編碼設定為utf-8即可。

public class EncodingFilter implements Filter {    @Override    public void destroy() {    }    @Override    public void doFilter(ServletRequest arg0, ServletResponse arg1,            FilterChain arg2) throws IOException, ServletException {        arg0.setCharacterEncoding("utf-8");        arg2.doFilter(arg0, arg1);    }    @Override    public void init(FilterConfig arg0) throws ServletException {    }}

配置如下:

<filter>    <filter-name>EncodingFilter</filter-name>    <filter-class>com.gavin.filter.EncodingFilter</filter-class></filter><filter-mapping>    <filter-name>EncodingFilter</filter-name>    <url-pattern>/*</url-pattern></filter-mapping>

(2)問題2:這裡我們儲存在伺服器的檔案名稱是使用者上傳的名稱,那麼如果有兩個使用者上傳的檔案名稱一樣就會出現覆蓋的情況,所以我們要在伺服器端進行檔案名稱的處理

這裡,我們不再使用使用者上傳的檔案的名稱。那麼又怎麼樣才能保證檔案名稱的唯一呢?

  • 1.一種方法是以當前的時間(年+月+日+時+分+秒+毫秒)作為檔案的名稱
  • 2.另外,可以直接使用java.util.UUID類,UUID不會重複,這種方法最為簡單。
String uuid = UUID.randomUUID().toString();
  • 3.當然,使用UUID之後,還要加上原來檔案的尾碼才行,所以乾脆寫一個工具類:
public class MyTools {    /**     * 得到檔案尾碼     * @param fileName     * @return     */    public static String getFileSuffix(String fileName) {        return fileName.substring(fileName.lastIndexOf("."));    }    /**     * 得到UUID     * @return     */    public static String getUUID(){        String uuid = UUID.randomUUID().toString();        return uuid;    }}

(3)問題3:如果使用者上傳的不是圖片怎麼辦?如果使用者上傳的圖片太大了怎麼辦?

所以這裡我們要進行檔案的限制,要進行檔案的類型和大小的限制,如果不符合要求,則跳轉至一個錯誤頁面並給出提示:
這裡我限制檔案的大小上限為10MB,如下:

if (fileSize > 10 * 1024 * 1024) {    request.setAttribute("error", "檔案大小不能超過10MB!");    return mapping.findForward("error");}if(!formFile.getContentType().startsWith("image/")){    request.setAttribute("error", "檔案格式有錯,請檢查!");    return mapping.findForward("error");}

【注意】檔案的類型是不是圖片,不是通過尾碼名來判斷的,要調用FormFile的方法,具體的檔案類型你可以查看Tomcat安裝目錄下的conf檔案夾下的web.xml檔案中的配置。

所以,最後,一個完整的RegisterAction是這樣的:

public class RegisterAction extends Action {    public ActionForward execute(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response) {        UserForm userForm = (UserForm) form;        String username = userForm.getName();        FormFile formFile = userForm.getPhoto();        // 通過FormFile我們可以擷取關於使用者上傳檔案的各種資訊,比如大小,名字等        String fileName = formFile.getFileName();        int fileSize = formFile.getFileSize();        if (fileSize > 10 * 1024 * 1024) {            request.setAttribute("error", "檔案大小不能超過10MB!");            return mapping.findForward("error");        }        if(!formFile.getContentType().startsWith("image/")){            request.setAttribute("error", "檔案格式有錯,請檢查!");            return mapping.findForward("error");        }        InputStream is = null;        OutputStream os = null;        String uuid = MyTools.getUUID();        String suffix = MyTools.getFileSuffix(fileName);        String newFileName = uuid + suffix;        try {            is = formFile.getInputStream();            String path = request.getServletContext().getRealPath("file");            System.out.println(path);            os = new FileOutputStream(path + "\\" + newFileName);            int len = 0;            byte[] bytes = new byte[1024];            while ((len = is.read(bytes)) > 0) {                os.write(bytes, 0, len);            }            //這裡省略儲存資料庫的操作            //邏輯上的正常跳轉,這裡也省略        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (os != null) {                    os.close();                }                if (is != null) {                    is.close();                }            } catch (Exception e2) {                e2.printStackTrace();            }        }        request.setAttribute("error", "註冊出錯!");        return mapping.findForward("error");    }}
2.Struts檔案下載

檔案下載,我們在介紹原生Servlet的時候已經介紹過,可以參考【Servlet——使用http回應標頭Content-Disposition下載檔案的樣本】。

當然,那時候我們是把下載的商務邏輯寫在一個Servlet中,這裡其實也沒有什麼不同,只不過我們要將商務邏輯寫在一個Struts的Action中,並且該Action不需要配置相應的表單。

當我們點擊下載的超連結時,讓它請求這個Action即可。並且最後讓該Action跳轉至原來的頁面:

return mapping.findForward("goback");

Struts1.3——檔案上傳和下載

聯繫我們

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