struts2文件上傳
來(lái)源:程序員人生 發(fā)布時(shí)間:2016-06-06 08:18:05 閱讀次數(shù):4095次
文件上傳
文件上傳幾近是每一個(gè)web利用實(shí)現(xiàn)的1個(gè)必須模塊。文件上傳的實(shí)現(xiàn)需要將表單元素屬性enctype的值設(shè)置為multipart/form-data,使表單數(shù)據(jù)以2進(jìn)制編碼的方式提交。在接收此要求的Servlet中使用2進(jìn)制流來(lái)獲得內(nèi)容,就能夠獲得上傳文件的內(nèi)容,從而實(shí)現(xiàn)文件的上傳。
上傳原理
在struts2中進(jìn)行文件上傳時(shí),先需要將Form表單的enctype屬性進(jìn)行重新設(shè)置,該屬性的取值就是決定表單數(shù)據(jù)的編碼方式,有以下3個(gè)可選值:
1)application/x-www-form-urlencoded.這是默許的編碼方式。只處理表單域里的value屬性值,采取這類編碼方式的表單會(huì)將表單域的值處理成URL編碼方式。
2)multipart/form-data.這類編碼方式的表單會(huì)以2進(jìn)制流的方式來(lái)處理表單數(shù)據(jù),將文件域指定文件的內(nèi)容也封裝到要求參數(shù)中。
3)text/plain.當(dāng)表單的action屬性值為mailto:URL的情勢(shì)時(shí),這類編碼方式比較方便,它主要適用于直接通過(guò)表單發(fā)送郵件。
文件上傳實(shí)例
實(shí)體類:
public class User {
private String name;//姓名
private String photo;//照片
private int age;//年齡
private int sex;//性別
private String icard;//身份證號(hào)
private String phone;//聯(lián)系電話
private String address;//聯(lián)系地址
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getIcard() {
return icard;
}
public void setIcard(String icard) {
this.icard = icard;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Action類:
public class UserAction extends ActionSupport {
private static final int BUFFER_SIZE = 40 * 40;
private File upload;// 封裝上傳文件域的
private String uploadContentType;// 封裝上傳文件的類型
private String uploadFileName;// 封裝上傳文件名
private String savePath;// 封裝上傳文件的保存路徑
private User user;// 創(chuàng)建User類對(duì)象user
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() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
private static void copy(File source, File target) {
InputStream inputStream = null;// 聲明1個(gè)輸入流
OutputStream outputStream = null;// 聲明1個(gè)輸出流
try {
// 實(shí)例化輸入流
inputStream = new BufferedInputStream(new FileInputStream(source),
BUFFER_SIZE);
outputStream = new BufferedOutputStream(
new FileOutputStream(target), BUFFER_SIZE);// 實(shí)例化輸出流
byte[] buffer = new byte[BUFFER_SIZE];// 定義字節(jié)數(shù)組buffer
int length = 0;// 定義臨時(shí)參數(shù)對(duì)象
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);// 如果上傳的文件字節(jié)數(shù)大于0,將內(nèi)容以字節(jié)情勢(shì)寫入
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();// 關(guān)閉輸入流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != outputStream) {
try {
outputStream.close();// 關(guān)閉輸出流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public String execute() throws Exception {
// 根據(jù)
服務(wù)器的文件保存地址和源文件名創(chuàng)建目錄文件全路徑
System.out.println("1" + this.getSavePath());
System.out.println("2" + this.getUploadFileName());
System.out.println("3" + this.getUpload());
System.out.println("4" + this.getTexts());
System.out.println("5" +this.getUploadContentType());
System.out.println("6" +ServletActionContext.getServletContext().getContextPath());
String path = ServletActionContext.getServletContext().getRealPath(
this.getSavePath())
+ "//" + this.getUploadFileName();
System.out.println(path);
System.out.println("uploadFilename: " + uploadFileName);
System.out.println("file: " + upload.getName());
System.out.println("file: " + upload.getPath());
user.setPhoto(this.uploadFileName);// 將上傳的文件名稱賦值給User類中的photo屬性
File target = new File(path);// 定義目標(biāo)文件對(duì)象
copy(this.upload, target);// 調(diào)用copy方法,實(shí)現(xiàn)文件的寫入
return SUCCESS;
}
}
struts.xml中的配置,
<action name="user" class="com.mxl.action.UserAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/pjpeg,image/x-png,image/gif,image/bmp
</param>
<param name="maximumSize">5000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<param name="savePath">/upload</param>
<result>/show_file.jsp</result>
<result name="input">/index.jsp</result>
</action>
上傳界面:
<s:form action="user" namespace="/" method="post" enctype="multipart/form-data">
<s:textfield name="user.name" label="姓名" size="20"/>
<s:file name="upload" label="形象" size="20"/>
<s:textfield name="user.age" label="年齡" size="20"/>
<s:radio list="#{1:'男',2:'女'}" name="user.sex" listKey="key" listValue="value" value="1" label="性別" cssStype="border:0px;"/>
<s:textfield name="user.icard" label="身份證號(hào)" size="20"/>
<s:textfield name="user.phone" label="聯(lián)系電話" size="20"/>
<s:textfield name="user.address" label="家庭住址" size="20"/>
<s:submit value="肯定錄入" align="center"/>
</s:form>
顯示界面:
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td width="300px" align="right">姓名:</td>
<td width="100px" align="left"><s:property value="user.name" />
</td>
<td rowspan="5" align="center"><img
src="upload/<s:property value="uploadFileName"/>"/><br />您的形象</td>
</tr>
<tr>
<td width="300px" align="right">年齡:</td>
<td><s:property value="user.age"/></td><td></td>
</tr>
<tr>
<td width="300px" align="right">性別:</td>
<td>
<s:if test="user.sex==1">
男
</s:if>
<s:else>
女
</s:else>
</td><td></td>
</tr>
<tr>
<td width="300px" align="right">身份證號(hào):</td>
<td><s:property value="user.icard"/></td><td></td>
</tr>
<tr>
<td width="300px" align="right">聯(lián)系電話:</td>
<td><s:property value="user.phone"/></td><td></td>
</tr>
<tr>
<td width="300px" align="right">家庭住址:</td>
<td><s:property value="user.address"/></td><td></td>
</tr>
</table>
多文件上傳實(shí)例:
數(shù)組實(shí)現(xiàn)多文件上傳,
Action類,
public class DocArrayAction extends ActionSupport{
private String name;//上傳者
private File[] upload;//封裝上傳文件的屬性
private String[] uploadContentType;//封裝上傳文件的類型
private String[] uploadFileName;//封裝上傳文件名
private String savePath;//封裝上傳文件保存路徑
private Date createTime;//上傳時(shí)間
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public Date getCreateTime(){//實(shí)例化日期
createTime = new Date();
return createTime;
}
private static void copy(File source, File target) {
InputStream inputStream = null;// 聲明1個(gè)輸入流
OutputStream outputStream = null;// 聲明1個(gè)輸出流
try {
// 實(shí)例化輸入流
inputStream = new BufferedInputStream(new FileInputStream(source));
outputStream = new BufferedOutputStream(
new FileOutputStream(target));// 實(shí)例化輸出流
byte[] buffer = new byte[1024];// 定義字節(jié)數(shù)組buffer
int length = 0;// 定義臨時(shí)參數(shù)對(duì)象
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);// 如果上傳的文件字節(jié)數(shù)大于0,將內(nèi)容以字節(jié)情勢(shì)寫入
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();// 關(guān)閉輸入流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != outputStream) {
try {
outputStream.close();// 關(guān)閉輸出流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public String execute() throws Exception {
for(int i = 0; i < upload.length; i++){
String path = ServletActionContext.getServletContext().getRealPath(
this.getSavePath())
+ "//" + this.uploadFileName[i];
File target = new File(path);// 定義目標(biāo)文件對(duì)象
copy(this.upload[i], target);// 調(diào)用copy方法,實(shí)現(xiàn)文件的寫入
}
return SUCCESS;
}
}
配置:
<action name="doc" class="com.mxl.action.DocArrayAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">50000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<param name="savePath">/upload</param>
<result>/show_doc.jsp</result>
<result name="input">/input_doc.jsp</result>
</action>
上傳界面:
<s:form action="doc" namespace="/" method="post" enctype="multipart/form-data">
<s:textfield name="name" label="姓名" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:submit value="肯定上傳" align="center"/>
</s:form>
上傳成功界面:
<font style="font-size:12px; color:red">上傳者<s:property value="name"/></font>
<table cellpadding="0" cellspacing="0">
<tr>
<th>文件名稱</th>
<th>上傳時(shí)間</th>
</tr>
<s:iterator value="uploadFileName" status="st">
<tr>
<td><s:property value="uploadFileName[#st.getIndex()]"/></td>
<td><s:date name="createTime" format="yyyy-MM-dd HH:mm:ss"/></td>
</tr>
</s:iterator>
</table>
List實(shí)現(xiàn)多文件上傳:
Action類:
public class DocListAction extends ActionSupport{
private String name;
private List<File> upload;
private List<String> uploadContentType;
private List<String> uploadFileName;
private String savePath;
private Date createTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<File> getUpload() {
return upload;
}
public void setUpload(List<File> upload) {
this.upload = upload;
}
public List<String> getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(List<String> uploadContentType) {
this.uploadContentType = uploadContentType;
}
public List<String> getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public Date getCreateTime(){
createTime = new Date();
return createTime;
}
public void setCreateTime(Date createTime){
this.createTime = createTime;
}
private static void copy(File source, File target) {
InputStream inputStream = null;// 聲明1個(gè)輸入流
OutputStream outputStream = null;// 聲明1個(gè)輸出流
try {
// 實(shí)例化輸入流
inputStream = new BufferedInputStream(new FileInputStream(source));
outputStream = new BufferedOutputStream(
new FileOutputStream(target));// 實(shí)例化輸出流
byte[] buffer = new byte[1024];// 定義字節(jié)數(shù)組buffer
int length = 0;// 定義臨時(shí)參數(shù)對(duì)象
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);// 如果上傳的文件字節(jié)數(shù)大于0,將內(nèi)容以字節(jié)情勢(shì)寫入
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();// 關(guān)閉輸入流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != outputStream) {
try {
outputStream.close();// 關(guān)閉輸出流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public String execute() throws Exception {
for(int i = 0; i < upload.size(); i++){
String path = ServletActionContext.getServletContext().getRealPath(
this.getSavePath())
+ "//" + this.uploadFileName.get(i);
File target = new File(path);// 定義目標(biāo)文件對(duì)象
copy(this.upload.get(i), target);// 調(diào)用copy方法,實(shí)現(xiàn)文件的寫入
}
return SUCCESS;
}
}
配置:
<action name="docList" class="com.mxl.action.DocListAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">50000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<param name="savePath">/upload</param>
<result>/show_docList.jsp</result>
<result name="input">/input_docList.jsp</result>
</action>
上傳界面:
<s:form action="docList" namespace="/" method="post" enctype="multipart/form-data">
<s:textfield name="name" label="姓名" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:file name="upload" label="選擇文檔" size="20"/>
<s:submit value="肯定上傳" align="center"/>
</s:form>
成功界面:
<font style="font-size:12px; color:red">上傳者<s:property value="name"/></font>
<table cellpadding="0" cellspacing="0">
<tr>
<th>文件名稱</th>
<th>上傳時(shí)間</th>
</tr>
<s:iterator value="uploadFileName" status="st" var="doc">
<tr>
<td><a href="downLoad.action?downPath=upload/<s:property value="#doc"/>"><s:property value="#doc"/></a></td>
<td><s:date name="createTime" format="yyyy-MM-dd HH:mm:ss"/></td>
</tr>
</s:iterator>
</table>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)