Struts2上传文件

来源:互联网 发布:网络it需要什么学历 编辑:程序博客网 时间:2024/04/24 00:37

在公司做过上传图片的功能,但是也是基于公司内部的插件做的,现在单独使用Struts2来实现文件的上传
一、上传单个文件
1.当然有的struts版本是要添加相关的jar包的,但是我的这个版本已经报喊了相关jar包,因此不需要额外添加了

2.先配置下struts.xml配置文件

<action name="uploadFile" class="action.UploadAction" method="uploadFile">        <result name="success">/WEB-INF/page/message.jsp</result></action>
3.再来看下JSP页面的主要代码

<form name="upload" action="uploadFile"  enctype="multipart/form-data" method="post">    上传文件:<input type="file" name="image"/><br/>      <input type="submit" value="上传"/></form>
注意:要有一个enctype的属性

4.最后看下action的关键代码

import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport{private File image;private String imageFileName;//获取文件名,固定格式,页面的name+FileNameprivate String imageContentType;public String uploadFile() throws Exception{//获得真实路径,用于保存上传的文件String realPath=ServletActionContext.getServletContext().getRealPath("/images");//System.out.println("realPath====="+realPath);if(image!=null){File saveFile=new File(realPath,imageFileName);System.out.println("saveFile====="+saveFile);System.out.println("imageContentType====="+imageContentType);if(!saveFile.getParentFile().exists()){saveFile.getParentFile().mkdirs();}FileUtils.copyFile(image, saveFile);}return SUCCESS;}//get、set省略...//这是上面打印的结果//realPath=====F:\apache-tomcat-6.0.36\webapps\struts2_Demo\images//saveFile=====F:\apache-tomcat-6.0.36\webapps\struts2_Demo\images\IMG0445A.jpg//  imageContentType=====image/jpeg}

注意:这里的两个变量,image要与页面中的name一样,imageFileName是上传的文件名,固定格式为:image(页面的name)+FileName。

二、上传多个文件

1.上传多个文件,struts配置文件不需要变动

2.JSP页面

<form name="upload" action="uploadFile"  enctype="multipart/form-data" method="post">文件1:<input type="file" name="image"><br/> 文件2:<input type="file" name="image"><br/> 文件3:<input type="file" name="image"><br/> <input type="submit" value="上传"/></form>

3.action关键代码

import java.io.File;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;public class HelloWorldAction {private File[] image;private String[] imageFileName;public String uploadFile() throws Exception{String realpath = ServletActionContext.getServletContext().getRealPath("/images");if(image!=null){File savedir = new File(realpath);if(!savedir.exists()){savedir.mkdirs();}for(int i = 0 ; i<image.length ; i++){File savefile = new File(savedir, imageFileName[i]);FileUtils.copyFile(image[i], savefile);}}return "success";}}}
注意:上传多个文件,这里的image和imageFileName要定义成数组。


0 0
原创粉丝点击