SSH学习(五)Struts2文件上传

来源:互联网 发布:淘宝虚拟物品店铺 编辑:程序博客网 时间:2024/06/06 06:29

原文来自搬砖工,如需转载请注明出处


博主SSH框架专栏请戳这里http://blog.csdn.net/column/details/14227.html

一、使用commons-fileupload上传文件

commons-fileupload是一个开源框架,要使用该项目实现文件上传需要使用两个文件:

1.commons-io.jar

2.commons-fileupload.jar

实现上传文件的步骤如下:

1.创建上传页面,注意form表单的enctype的属性值应为“multipart/form-data”

2.创建servlet调用commons-fileupload API实现文件上传 

示例代码如下:

上传页面form表单

<form name="" id="" action="/servlet/UploadServlet" enctype="multipart/form-data" method="post"><table border="0"><tr><td>File:</td><td><input type="file" name="f" /></td></tr><tr><td colspan="2" align="center" ><input type="submit"/></td></tr></table></form>
然后创建一个servlet,重新UploadServlet的doPost方法:

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);try {List items = upload.parseRequest(request);Iterator iter = items.iterator();while(iter.hasNext()){FileItem item = (FileItem) iter.next();if(item.isFormField()){System.out.println(item.getFieldName());}else{System.out.println(item.getFieldName());String filename = item.getName();System.out.println(filename);String path = this.getServletContext().getRealPath("\\file");File file = new File(path+"\\"+filename);item.write(file);}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
注意:表单在设置参数的时候必须加上method=post,否则后台会报错。

二、使用Struts2上传文件

首先创建一个UploadAction

package com.study.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 UploadAction extends ActionSupport{private File upload;private String uploadContentType;private String uploadFileName;private String savePath;public String execute() throws Exception {String path = this.getSavePath();String filename = this.getUploadFileName();System.out.println(path);System.out.println(filename);FileOutputStream out = new FileOutputStream(path+"//"+filename);FileInputStream in = new FileInputStream(this.getUpload());byte[]b = new byte[in.available()];in.read(b);out.write(b);in.close();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() {savePath = ServletActionContext.getServletContext().getRealPath("//file");return savePath;}public void setSavePath(String savePath) {this.savePath = savePath;}}
在Action中包含了如下参数,一个File对象upload,文件名称uploadFileName,ContentType是uploadContentType还有一个保存路径savePath。在Struts2中,根据特有的命名规则,根据upload文件对象就可以给uploadFileName赋真实的文件名称。而upload实际中是取得的一个临时文件。最后保存到我们指定的路径下。

struts.xml中的配置:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><constant name="struts.multipart.saveDir" value="c:\\temp"></constant><package name="example" namespace="/" extends="struts-default"> <action name="upload" class="com.study.action.UploadAction"><result name="success">/Success.jsp</result><param name="savePath">/file</param></action></package></struts>    
在配置中,我们指定一个临时文件路径struts.multipart.saveDir,自己创建一个文件夹来当做临时文件夹。临时文件在文件操作完毕后会自动删除。然后我们在action中声明一个参数savePath,它的值就是/file。对于如何根据upload取得uploadFileName,大家可以理解为将upload当做参数{1},然后文件名属性就是*FileName。其他的同理。

然后就是一个简单的jsp页面

<form name="" id="" action="<%= path%>/upload.action" enctype="multipart/form-data" method="post"><table border="0"><tr><td>File:</td><td><input type="file" name="upload" /></td></tr><tr><td colspan="2" align="center" ><input type="submit"/></td></tr></table></form>
注意,在这里的input就必须定义名称name,它的值就是我们后台所命名的属性值名称。

三、多个文件上传

对于同时提交多个文件,我们需要把Action中的属性定义为数组类型或list类型。在文件读写的时候用for循环取出所有文件即可,如:

package com.study.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;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 Exception {String path = this.getSavePath();for (int i = 0; i < upload.length; i++) {String filename = this.getUploadFileName()[i];System.out.println(path);System.out.println(filename);FileOutputStream out = new FileOutputStream(path+"//"+filename);FileInputStream in = new FileInputStream(this.getUpload()[i]);byte[]b = new byte[in.available()];in.read(b);out.write(b);in.close();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;}}
:在Struts2中还可以使用它的标签来作文件上传
3 0