struts2 上传单个文件

一、新建包cn.xs.fileupload,并建立FileUploadAction.java文件,内容如下:
// ---------------------------------------------------------
// @author    sheng.xu
// @version   1.0.0
// @date	2014年6月8日
// ---------------------------------------------------------
package cn.xs.fileupload;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;


/**
 * @author sheng.xu
 *
 */
public class FileUploadAction {
	private File image;//获取文件
	private String imageFileName;//获取文件名称
	private String imageContentType;//获取文件类型
	/**
	 * @return the image
	 */
	public File getImage() {
		return image;
	}
	/**
	 * @param image the image to set
	 */
	public void setImage(File image) {
		this.image = image;
	} 
	/**
	 * @return the imageFileName
	 */
	public String getImageFileName() {
		return imageFileName;
	}
	/**
	 * @param imageFileName the imageFileName to set
	 */
	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}
	public String execute() throws IOException {
		String realpath = ServletActionContext.getServletContext().getRealPath("/images");//获取文件上传后的存放目录的绝对路径
		System.out.println(realpath);
		if(image != null){
			File savefile = new File(new File(realpath),imageFileName);
			if(!savefile.getParentFile().exists()) {
				savefile.getParentFile().mkdirs();
			}
			FileUtils.copyFile(image, savefile);
			ActionContext.getContext().put("message", "上传成功");
		}
		return "success";
	}
	public String requestFile(){
		return "success";
	}
}

二、建立对应的jsp文件:fileupload.jsp内容如下: 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <form action="${pageContext.request.contextPath}/test3/fileupload_execute.action" enctype="multipart/form-data" method="post">
    	文件:<input type="file" name="image">
    	<input type="submit" value="上传"/>
    </form>
    {$message}
</body>
</html>
三、建立struts.xml中配置action如下:

<action name="fileupload_*" class="cn.xs.fileupload.FileUploadAction" method = "{1}">
	<!-- 配置返回结果 -->
	<result name="success">/WEB-INF/page/fileupload.jsp</result>
	<result name="error">/error.jsp</result>
</action>
四、访问http://localhost:8080/Struts2/test3/fileupload_requestFile.action

注:上传文件大小的限制,可以在struts.xml文件中加入如下配置:<constant name="struts.mutipart.maxSize" value="10701096">

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值