Struts文件上传与下载详解 _上传多个文件
在上一篇中给大家列出的单个文件的上传,那么这一篇咱们讲讲上传多个文件改怎么作呢?由于过程和上传单个文件的类似,所以在这里不细说,相信大家都能看懂,看不懂的可以在评论区留言,我看到之后会及时回复的!!
咱们开门见山的来吧
1.创建个jsp表单页面,主要就是上传多个文件:
<body>
<s:form action="upload.action" method="post" enctype="multipart/form-data">
<s:textfield name="file" label="标题"/><br/>
<%-- <s:file name="upload" label="选择文件"/><br/> --%>
<s:file name="mupload" label="选择文件1"/><br/>
<s:file name="mupload" label="选择文件2"/><br/>
<s:file name="mupload" label="选择文件3"/><br/>
<s:submit name="submit" value="上传文件"/>
</s:form>
</body>
2.我们接下来去写一下UploadAction里面:
package org.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File[] mupload; //封装上传文件的属性(多个)
private String[] muploadContentType; //封装上传文件的类型(多个)
private String[] muploadFileName; //封装上传文件的名称(多个)
private String msavePath; //获取文件上传的路径(多个)
//实现文件的多个上传
public String execute() throws IOException{
byte[] buffer=new byte[1024];
for (int i = 0; i < mupload.length; i++) {
//获取物理路径"/upload"
String path=ServletActionContext.getServletContext().getRealPath(savePath);
FileInputStream fis=new FileInputStream(getMupload()[i]);
FileOutputStream fos=new FileOutputStream(path+"/"+getMuploadFileName()[i]);
int length=fis.read(buffer);
while (length>0) {
//每次写入length长度的内容
fos.write(buffer,0,length);
length=fis.read(buffer);
}
fis.close();
fos.flush();
fos.close();
}
return SUCCESS;
}
public File[] getMupload() {
return mupload;
}
public void setMupload(File[] mupload) {
this.mupload = mupload;
}
public String[] getMuploadContentType() {
return muploadContentType;
}
public void setMuploadContentType(String[] muploadContentType) {
this.muploadContentType = muploadContentType;
}
public String[] getMuploadFileName() {
return muploadFileName;
}
public void setMuploadFileName(String[] muploadFileName) {
this.muploadFileName = muploadFileName;
}
public String getMsavePath() {
return msavePath;
}
public void setMsavePath(String msavePath) {
this.msavePath = msavePath;
}
}
3.nice,这里面已经搞定,咱们就移步到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>
<package name="default" namespace="/" extends="struts-default">
<!-- 文件上传 -->
<action name="upload" class="org.web.UploadAction">
<param name="savePath">/upload</param>
<result name="success">/upload_suc.jsp</result>
</action>
</package>
</struts>
最后发布运行就OK了。