struts2实现文件上传

实现文件上传的方式有很多种,如smartupload,输入输出流以及其他方式。struts2也提供了文件上传给开发人员,相比之下struts2的文件上传更加简单快速。在开发中文件上传是比不可少的,因此这也是一个比较重要的知识点。下面就来写一下struts2的文件上传。

1.写一个表单用来选择文件

这里不能忘记写enctype="multipart/form-data",这一点在开发中可能会被遗漏

<%@ 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>struts2文件上传</title>
</head>
<body>
  <form action="uploadAction.action" enctype="multipart/form-data" method="post">
    选择文件:<input type="file"/ name="picture"> <!-- 这里的picture和后面的action里的必须一致 -->
    <input type="submit" value="上传"/>
  </form>
</body>
</html>

文件上传使用的提交方式必须使用post提交,原因相信大家都知道。

2.写一个处理文件上传的action

这里需要注意,名称要和表单里的name保持一致,这是struts2的一些规定

package org.lxh.action;

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

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

public class UploadAction {
	private File picture;
	private String pictureFileName;  //FileName是固定写法,前面的picture就是表单里的name属性
	private String pictureContentType;

	public File getPicture() {
		return picture;
	}

	public void setPicture(File picture) {
		this.picture = picture;
	}

	public String getPictureFileName() {
		return pictureFileName;
	}

	public void setPictureFileName(String pictureFileName) {
		this.pictureFileName = pictureFileName;
	}

	public String getPictureContentType() {
		return pictureContentType;
	}

	public void setPictureContentType(String pictureContentType) {
		this.pictureContentType = pictureContentType;
	}
	
	public String upload() throws Exception {
		String flag="failure";
     //取得真实目录
		String path=ServletActionContext.getServletContext().getRealPath("/image");
		File file=new File(path,pictureFileName);
		//如果目录不存在就创建一个
		if(!file.getParentFile().exists()) 
		file.getParentFile().mkdirs();
		//使用FileUtil工具类保存文件,这里不能少了commons-io包
		
		if(picture!=null){  
			FileUtils.copyFile(picture, file);
			ServletActionContext.getContext().put("tip", "成功");
			flag="success";
			
		}else{
			ServletActionContext.getContext().put("tip", "失败");
		}
		return flag;
		
	}
}

这里需要使用一个工具类,需要commons-io包的支持,另外要对文件目录做判断,如果不存在就创建目录。之后保存一个提示信息,在结果页面显示。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值