鍍金池/ 教程/ Java/ 文件上傳
注釋
主題/模板
驗(yàn)證
有用的資源
Struts 2 注解類型
實(shí)例
攔截器
異常處理
表單標(biāo)簽
結(jié)果類型
值棧/OGNL
Spring 集成
數(shù)據(jù)標(biāo)簽
環(huán)境配置
配置
類型轉(zhuǎn)換
動(dòng)作
Hibernate 集成
本地化
發(fā)送郵件
Ajax 標(biāo)簽
數(shù)據(jù)庫(kù)訪問
體系結(jié)構(gòu)
文件上傳
Tiles 集成
概述
基本的 MVC 架構(gòu)
控制標(biāo)簽

文件上傳

Struts 2 框架為處理文件上傳提供了內(nèi)置支持,它使用“在 HTML 中基于表單的文件上傳”。當(dāng)上傳一個(gè)文件時(shí),它通常會(huì)被存儲(chǔ)在一個(gè)臨時(shí)目錄中,而且它們應(yīng)該由 Action 類進(jìn)行處理或移動(dòng)到一個(gè)永久的目錄,用來確保數(shù)據(jù)不丟失。

注意服務(wù)器在恰當(dāng)?shù)奈恢每赡苡幸粋€(gè)安全策略,它會(huì)禁止你寫到除了臨時(shí)目錄以外的目錄,而且這個(gè)目錄屬于你的web應(yīng)用應(yīng)用程序。

通過預(yù)定義的名為文件上傳的攔截器,Struts 的文件上傳是可能的,這個(gè)攔截器在 org.apache.struts2.interceptor.FileUploadInterceptor 類是可用的,而且是 defaultStack 的一部分。你仍然可以使用在 struts.xml 中設(shè)置各種參數(shù),我們將在下面看到。

創(chuàng)建視圖文件

讓我們開始創(chuàng)建需要瀏覽和上傳選定的文件的視圖。因此,讓我們創(chuàng)建一個(gè)帶有簡(jiǎn)單的 HTML 上傳表單的 index.jsp,它允許用戶上傳文件:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
</head>
<body>
   <form action="upload" method="post" enctype="multipart/form-data">
      <label for="myFile">Upload your file</label>
      <input type="file" name="myFile" />
      <input type="submit" value="Upload"/>
   </form>
</body>
</html>

在上面的例子中有幾點(diǎn)值得注意。首先,表單的編碼類型設(shè)置為 multipart/form-data。為了使用文件上傳攔截器來成功地處理文件上傳,它應(yīng)該被設(shè)置。下一個(gè)注意點(diǎn)是表單的動(dòng)作方法 upload 和文件上傳字段的名稱是 myFile。我們需要這些信息來創(chuàng)建動(dòng)作方法和 struts 配置。

接下來讓我們創(chuàng)建一個(gè)簡(jiǎn)單的 jsp 文件 success.jsp 來顯示我們的文件上傳的結(jié)果,假使它成功地執(zhí)行。

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>

下面是結(jié)果文件 error.jsp,假使在上傳文件過程中有一些錯(cuò)誤:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Error</title>
</head>
<body>
There has been an error in uploading the file.
</body>
</html>

創(chuàng)建 action 類

接下來讓我們創(chuàng)建一個(gè)稱為 uploadFile.java 的 Java 類,它負(fù)責(zé)上傳文件,并且把這個(gè)文件存儲(chǔ)在一個(gè)安全的位置:

package com.tutorialspoint.struts2;
import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException; 
import com.opensymphony.xwork2.ActionSupport;
public class uploadFile extends ActionSupport{
   private File myFile;
   private String myFileContentType;
   private String myFileFileName;
   private String destPath;
   public String execute()
   {
      /* Copy file to a safe location */
      destPath = "C:/apache-tomcat-6.0.33/work/";
      try{
         System.out.println("Src File name: " + myFile);
         System.out.println("Dst File name: " + myFileFileName);             
         File destFile  = new File(destPath, myFileFileName);
         FileUtils.copyFile(myFile, destFile);  
      }catch(IOException e){
         e.printStackTrace();
         return ERROR;
      }
      return SUCCESS;
   }
   public File getMyFile() {
      return myFile;
   }
   public void setMyFile(File myFile) {
      this.myFile = myFile;
   }
   public String getMyFileContentType() {
      return myFileContentType;
   }
   public void setMyFileContentType(String myFileContentType) {
      this.myFileContentType = myFileContentType;
   }
   public String getMyFileFileName() {
      return myFileFileName;
   }
   public void setMyFileFileName(String myFileFileName) {
      this.myFileFileName = myFileFileName;
   }
}

uploadFile.java 是一個(gè)非常簡(jiǎn)單的類。值得注意的一件重要的事情是文件上傳攔截器和參數(shù)攔截器為我們處理所有繁重的工作。文件上傳攔截器在默認(rèn)情況下有三個(gè)可用的參數(shù)。它們被命名為下列模式:

  • [your file name parameter] –這是實(shí)際的用戶已經(jīng)上傳的文件。在這個(gè)例子中它是 “myFile”。

  • [your file name parameter]ContentType - 這是被上傳的文件的內(nèi)容類型。在這個(gè)例子中它是 “myFileContentType”。

  • [your file name parameter]FileName - 這是被上傳的文件的名稱。在這個(gè)例子中它是 “myFileFileName”。

對(duì)我們來說,這三個(gè)參數(shù)是可用的,這要?dú)w功于 Struts 的攔截器。我們要做的是在我們的動(dòng)作類中用正確的名稱創(chuàng)建三個(gè)參數(shù),而且這些變量是為我們自動(dòng)連線的。所以,在上面的例子中,我們有三個(gè)參數(shù)和一個(gè)動(dòng)作方法,如果一切正常,則簡(jiǎn)單地返回 “success”,否則返回 “error”。

配置文件

下面是可以控制文件上傳過程的 Struts2 的配置屬性:

序號(hào) 屬性 & 描述
1 struts.multipart.maxSize

當(dāng)一個(gè)文件上傳時(shí),可以接受的最大的文件大小(以字節(jié)為單位)。默認(rèn)設(shè)置是 250 M。

2 struts.multipart.parser

用于上傳多個(gè)表單的庫(kù)。默認(rèn)情況下是 jakarta。

3 struts.multipart.saveDir

存儲(chǔ)臨時(shí)文件的位置。默認(rèn)情況下是 javax.servlet.context.tempdir。

為了改變這些設(shè)置,你可以使用在你的應(yīng)用程序 struts.xml 文件中 constant 標(biāo)簽,就像我改變上傳文件的最大大小的操作。讓我們有如下所示的 struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name="struts.devMode" value="true" />
   <constant name="struts.multipart.maxSize" value="1000000" />
   <package name="helloworld" extends="struts-default">
   <action name="upload" class="com.tutorialspoint.struts2.uploadFile">
       <result name="success">/success.jsp</result>
       <result name="error">/error.jsp</result>
   </action>
   </package>
</struts>

由于攔截器是攔截器 defaultStack 的一部分,我們并不需要明確地配置它。但是你可以在 里面添加 標(biāo)簽。文件上傳攔截器需要兩個(gè)參數(shù):(a)maximumSize(b)allowedTypes。maximumSize 參數(shù)設(shè)置允許的最大文件大小(默認(rèn)為約 2 MB)。allowedTypes 參數(shù)是一個(gè)逗號(hào)分隔的公認(rèn)的內(nèi)容(MIME)類型列表,如下所示:

<action name="upload" class="com.tutorialspoint.struts2.uploadFile">
       <interceptor-ref name="basicStack">
       <interceptor-ref name="fileUpload">
           <param name="allowedTypes">image/jpeg,image/gif</param>
       </interceptor-ref>
       <result name="success">/success.jsp</result>
       <result name="error">/error.jsp</result>
   </action>

下面是 web.xml 文件的內(nèi)容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>
   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

現(xiàn)在,在項(xiàng)目名稱上點(diǎn)擊右鍵,并且單擊 Export > WAR File 來創(chuàng)建一個(gè) War 文件。然后在 Tomcat 的 webapps 目錄下部署這個(gè) WAR。最后,啟動(dòng) Tomcat 服務(wù)器和嘗試訪問 URL http://localhost:8080/HelloWorldStruts2/upload.jsp. 將會(huì)給出下面的畫面:

http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts7.jpg" alt="" />

現(xiàn)在使用瀏覽按鈕選擇一個(gè)文件 “Contacts.txt”,而且單擊上傳按鈕,它將在你的服務(wù)器上上傳文件,然后你應(yīng)該看到頁面。你可以查看保存在 C:\apache-tomcat-6.0.33\work 中上傳的文件。

http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts8.jpg" alt="" />

注意文件上傳攔截器自動(dòng)刪除上傳的文件,所以你需要通過編程在某個(gè)位置上保存上傳的文件,在它被刪除之前。

錯(cuò)誤消息

文件上傳攔截器使用幾個(gè)默認(rèn)的錯(cuò)誤消息鍵:

序號(hào) 錯(cuò)誤消息鍵 & 描述
1 struts.messages.error.uploading

一個(gè)發(fā)生在文件無法上傳時(shí)的通常的錯(cuò)誤。

2 struts.messages.error.file.too.large

發(fā)生在上傳文件比指定的 maximumSize 大時(shí)。

3 struts.messages.error.content.type.not.allowed

發(fā)生在上傳文件不匹配指定的預(yù)期內(nèi)容類型。

你可以重寫在 WebContent/WEB-INF/classes/messages.properties 源文件中消息的內(nèi)容。

上一篇:主題/模板下一篇:Ajax 標(biāo)簽