Struts2實現檔案上傳功能,struts2實現檔案上傳

來源:互聯網
上載者:User

Struts2實現檔案上傳功能,struts2實現檔案上傳

Servlet 3.0規範的HttpServletRequest已經提供了方法來處理檔案上傳但這種上傳需要在Servlet中完成。而Struts2則提供了更簡單的封裝。

Struts2預設使用的是Jakarta的Common-FileUpload的檔案上傳架構,因此使用Struts2的檔案上傳功能,則需要添加兩個jar包,即commons-io-2.2.jar和commons-fileupload-1.3.1.jar。 

Struts2簡單檔案上傳樣本:

1.檔案上傳頁面

  為了能上傳檔案,表單的method必須設定為POST,並且enctype設定為multipart/form-data。一旦設定了enctype為multipart/form-data,此時瀏覽器將會採用二進位流的方式來處理表單資料。

<%@ taglib prefix="s" uri="/struts-tags" %><%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/1/16 Time: 14:06 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Struts2 簡單檔案上傳</title></head><body> <s:form action="file_upload" method="POST" enctype="multipart/form-data"> <s:file name="upload" label="選擇檔案"/> <s:submit value="上傳"/> </s:form></body></html>

2.處理上傳請求的Action

/** * Description:Struts2簡單檔案上傳 * Author: Eleven * Date: 2018/1/24 10:39 */public class FileAction extends ActionSupport{ //上傳檔案 private File upload; //上傳檔案類型 private String uploadContentType; //上傳檔案名稱 private String uploadFileName; //檔案上傳允許的類型在struts.xml中使用param標籤動態設定了 private String allowTypes; public String page(){ return "page"; } public void upload() { //檔案上傳: //1.讀取檔案內容 //2.將檔案內容寫到指定檔案 try{  System.out.println("檔案上傳允許的類型="+allowTypes);  String realPath = ServletActionContext.getServletContext().getRealPath("/upload");  System.out.println("項目的絕對路徑="+realPath);  //建立檔案儲存目錄  new File(realPath).mkdir();  File file = new File(realPath+"/"+uploadFileName);  //檔案不存在則建立  if(!file.exists()){  file.createNewFile();  }  FileOutputStream out = new FileOutputStream(file);  FileInputStream in = new FileInputStream(upload);  byte[] buffer = new byte[1024];  int len = 0;  //邊讀邊寫 每次讀取1kb 寫1kb  while((len = in.read(buffer))>0){  out.write(buffer,0,len);  }  System.out.println("檔案上傳成功..."); }catch(Exception e){  e.printStackTrace(); } } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public String getAllowTypes() { return allowTypes; } public void setAllowTypes(String allowTypes) { this.allowTypes = allowTypes; }}

如果表單中包含一個name屬性為xxx的檔案域,則對應的Action中需要使用三個成員變數來封裝該檔案域的資訊。

  類型為File的xxx成員變數封裝了該檔案域對應的檔案內容。

  類型為String的xxxFileName成員變數封裝了該檔案域對應的檔案的檔案名稱。

  類型為String的xxxContentType成員變數封裝了該檔案域對應的檔案的檔案類型。

3.配置struts.xml

<?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.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!--檔案上傳--> <action name="file_*" class="eleven.action.FileAction" method="{1}">  <result name="page">/WEB-INF/jsp/fileUpload.jsp</result>  <!--動態設定action的屬性,這裡舉例設定了允許檔案上傳的類型,但是action程式中並未做過多的處理-->  <param name="allowTypes">image/png,image/gif,image/jpeg</param> </action> </package></struts>

攔截器實現檔案過濾  

  Struts2提供了一個檔案上傳的攔截器,fileUpload,為了讓該攔截器起作用,要在action中配置攔截器引用。

  配置fileUpload攔截器時,可以為其指定兩個參數:

    allowTypes:允許上傳的檔案類型,多個檔案類型之間用英文逗號,隔開

    maximumSize:允許上傳的檔案大小,單位是位元組。

  當檔案過濾失敗後,系統自動轉入input邏輯視圖,因此必須為該Action配置名為input的邏輯視圖。除此之外,還必須顯示地為該Action配置defaultStack的攔截器引用。

struts.xml設定檔如下:

<?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.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!--檔案上傳--> <action name="file_*" class="eleven.action.FileAction" method="{1}">  <!--配置fileUpload攔截器 且配置在defaultStack攔截器棧之前-->  <interceptor-ref name="fileUpload">  <!--允許上傳的檔案類型-->  <param name="allowedTypes">image/png,image/gif,image/jpeg</param>  <!--允許上傳檔案大小-->  <param name="maximumSize">2000</param>  </interceptor-ref>  <!--配置系統預設攔截器-->  <interceptor-ref name="defaultStack"/>  <!--配置input視圖頁面-->  <result name="input">/WEB-INF/jsp/input.jsp</result>  <result name="page">/WEB-INF/jsp/fileUpload.jsp</result> </action> </package></struts>

  上面配置的檔案上傳的攔截器,要求檔案上傳的類型只能是圖片檔案,並且檔案大小不能大於2000位元組,如果上傳檔案太大,或者類型不符合,則將跳轉到input邏輯視圖。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

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