大家都知道Servlet上传文件的时候用的是commons-fileupload插件上传的,但是过程极其的麻烦,同样Struts2也有自带的文件上传,但是过程比Servlet里面的简单了不少,接下来请大家看演示:
我们现在先建一个表单用于上传文件:
<s:form action="upload.action" method="post" enctype="multipart/form-data"> <s:textfield name="file" label="标题"/><br/> <s:file name="upload" label="选择文件"/><br/> </s:form>
这个很简单,主要就是用的Struts的标签展示出来的,这里不多做解释,然后我们再写个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 upload; //封装上传文件的属性(单个) private String uploadContentType; //封装上传文件的类型(单个) private String uploadFileName; //封装上传文件的名称(单个) private String savePath; //获取文件上传的路径(单个) //实现文件的单个上传 public String execute() throws IOException{ byte[]by=new byte[1024]; //获取物理路径"/upload" String path=ServletActionContext.getServletContext().getRealPath(savePath); FileInputStream in = new FileInputStream(getUpload()); FileOutputStream out=new FileOutputStream(path+"\\"+getUploadFileName()); int i=in.read(by); while(i>0){ out.write(by,0,i); i=in.read(by); } in.close(); out.flush(); out.close(); return SUCCESS; } 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; } }
需要注意的是:由于文件上传到了/upload目录下面,所以咱们得先在WebRoot下面创建一个文件夹“upload”,上传的所有的文件都在这个目录下面。
接着我们来配置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>
然后我们就可以发布运行了。
注意:
1.execute的方法千万别写错,要不然上传不到服务器upload里面。
2.UploadAction里面File upload,此处的upload必须要和jsp里面的name的值一样
3.文件类型命名:upload+ContentType