Struts 2框架提供了內(nèi)置支持處理文件上傳使用基于HTML表單的文件上傳。上傳一個(gè)文件時(shí),它通常會(huì)被存儲(chǔ)在一個(gè)臨時(shí)目錄中,他們應(yīng)該由Action類(lèi)進(jìn)行處理或移動(dòng)到一個(gè)永久的目錄,以確保數(shù)據(jù)不丟失。
請(qǐng)注意,服務(wù)器有一個(gè)安全策略可能會(huì)禁止寫(xiě)到目錄以外的臨時(shí)目錄和屬于web應(yīng)用的目錄。
在Struts中的文件上傳是通過(guò)預(yù)先定義的攔截文件上傳攔截器這是可通過(guò)org.apache.struts2.interceptor.FileUploadInterceptor類(lèi)的defaultStack中的一部分。仍然可以使用在struts.xml中設(shè)置各種參數(shù),我們將在下面看到。
讓我們開(kāi)始創(chuàng)建我們認(rèn)為這將需要瀏覽和上傳選定的文件。因此,讓我們創(chuàng)建一個(gè)純HTML上傳表單,允許用戶(hù)上傳文件 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)說(shuō)明。首先,表單的enctype屬性設(shè)置為multipart/ form-data。這應(yīng)該是設(shè)置為使得處理文件上傳文件上傳。下一個(gè)點(diǎn)值得注意的是表單的 action方法上傳和文件上傳字段的名稱(chēng) - myFile。我們需要這些信息創(chuàng)建操作方法和struts配置。
接下來(lái)讓我們創(chuàng)建一個(gè)簡(jiǎn)單的 jsp 文件的success.jsp 結(jié)果顯示我們的文件上傳的情況下成功。
<%@ 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 可能會(huì)有一些錯(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>
接下來(lái)讓我們創(chuàng)建一個(gè)Java類(lèi)稱(chēng)為 uploadFile.java 這會(huì)處理上傳文件,該文件存儲(chǔ)在一個(gè)安全的位置:
package com.yiibai.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上一篇:Struts2 url標(biāo)簽下一篇:Struts2獲取HttpServletResponse實(shí)例