首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Struts2处理文件下传

2012-08-22 
Struts2处理文件上传一.处理单个文件的上传操作需要的jar包:commons-io-1.3.2.jarcommons-fileupload-1.2.

Struts2处理文件上传
一.处理单个文件的上传操作
需要的jar包:
commons-io-1.3.2.jar
commons-fileupload-1.2.1.jar
及Struts的jar包


1.fileUpload.jsp

 <body>    <form action="fileUpload.action" method="post" enctype="multipart/form-data">    username: <input type="text" name="username"><br>    file: <input type="file" name="file"><br>    <input type="submit" value="submit">    </form>  </body>


2.FileUploadAction

package com.eric.struts2;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;/** *  * @author eric 上传单个文件 */public class UploadAction extends ActionSupport {private String username;// 获取上传的文件名称:file为前台jsp中 input type=file 的name值private File file;// 获取上传的文件名称:固定格式 file + FileNameprivate String fileFileName;// 获取上传的文件类型mime类型:固定格式 file + ContentTypeprivate String fileContentType;         //file.getName()方法得到的是上传的临时文件的名字public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public File getFile() {return file;}public void setFile(File file) {this.file = file;}public String getFileFileName() {return fileFileName;}public void setFileFileName(String fileFileName) {this.fileFileName = fileFileName;}public String getFileContentType() {return fileContentType;}public void setFileContentType(String fileContentType) {this.fileContentType = fileContentType;}/** * 处理文件上传的方法 */@Overridepublic String execute() throws Exception {//取得存放上传文件的目录路径String root = ServletActionContext.getRequest().getRealPath("/upload");//文件上传,IO操作,写到磁盘目录中去InputStream is = new FileInputStream(file);System.out.println("path: " + file.getAbsolutePath());System.out.println("file: " + file.getName());System.out.println("fileFileName: " + fileFileName);File destFile = new File(root, fileFileName);OutputStream os = new FileOutputStream(destFile);byte[] buffer = new byte[400];int length = 0;while (-1 != (length = is.read(buffer))) {os.write(buffer, 0, length);//Thread.sleep(1000);}is.close();os.close();return SUCCESS;}}


3.struts.xml

<action name="fileUpload" name="code"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>  <body>    username: <s:property value="username"/><br>    name:<s:property value="fileFileName"/><br>    type:<s:property value="fileContentType"/>  </body>

热点排行