本文主要介紹struts2文件上傳的簡要操作步驟。目前我使用的版本是2.3.34。其實大致思路還是關於IO流的讀寫和struts1版本的實現思路是一樣的,就是說先從頁面中獲得一個文件輸入流,再根據輸入流創建一個輸出流,將文件寫到一個文件夾中。具體步驟如下 :
首先我們先創建一個action代碼如下:
package com.ev.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport{
private File upload;
private String uploadContentType;
private String uploadFileName;
private String savePath;
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 getSavePath() {
savePath = ServletActionContext.getServletContext().getRealPath("\\upload");
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
@Override
public String execute() throws Exception {
File file = this.getUpload();
String fileName = this.getUploadFileName();
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(this.getSavePath()+"\\"+fileName);
System.out.println(this.getSavePath()+fileName);
byte[] arr = new byte[in.available()];
in.read(arr);
out.write(arr);
in.close();
out.close();
return SUCCESS;
}
}
這裏需要注意的是upload成員與jsp頁面中的文件域中的name屬性值是一致的。這裏的數據類型是java.io.File;這個在底層struts2已經幫我們封裝好了,所以才能用這個類型,還有就是uploadContentTypet和uploadFileName成員分別是upload接ContentType和FileName;也就是說後面部分是固定不變的。savePath是文件上傳後的保存路徑。action後臺代碼寫好後還要對其做一下配置如下(該配置寫在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="/path" extends="struts-default">
<action name="uploadAction" class="com.ev.action.MyAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
最後我們就可以在jsp頁面中調用該action實現文件上傳了,jsp代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/struts2fileupload/path/uploadAction.action" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="upload" /><br/>
<input type="submit" value="上傳">
</form>
</body>
</html>
本次上傳的文件位於upload目錄下