如何使用struts2上传文件

1.

单文件上传

上传文件对表单的要求:

1. 表单要使用post方式提交

2.  表单的enctype是multipart/form-data

3.  表单中要有file类型的input文本域

Struts上传也是基于拦截器,底层还是使用commons-fileupload组件

Struts上传的步骤

(1)      建立表单

<form action="${pageContext.request.contextPath }/upload/renliang" method="post" enctype="multipart/form-data">
	姓名:<input type="text" name="username"><br>
	文件:<input type="file" name="upload"><br>
	<input type="submit">
</form>

(2)创建Action

注意:

接收的文件属性:和表单中文本域file类型input的name一致

接收的文件名字:file的name+FileName固定写法[固定写法,应该是表单中File类型的input的name属性值+FileName]

接收的文件MIME类型:file的name+ContentType[固定写法,应该是表单中File类型的input的name属性值+ContextType;]

action代码:

public class UploadAction extends ActionSupport{
	

	private String username;
	
	/**
	 * 要接收的文件,命名需要和表单中的file类型的input的name一致
	 */		
	private File upload;
	
	/**
	 * 文件名的接收 File属性名FileName:固定写法
	 */
	private String uploadFileName;
	
	/**
	 * 获得上传文件的MIME类型,File属性名字ContentType:固定写法
	 */
	private String uploadContentType;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	
	
	public String upload() throws Exception{
		//获得servletContext
		ServletContext sc = ServletActionContext.getServletContext();
		//获得服务的绝对路径
		String realPath = sc.getRealPath("/");
		realPath = realPath + "upload\\"+uploadFileName;
		//定义输入输出流
		InputStream in = new FileInputStream(upload);
		OutputStream out = new FileOutputStream(realPath);
		int len = -1;
		byte[] bs = new byte[1024];
		while((len = in.read(bs)) != -1){
			out.write(bs, 0, len);
		}
		out.close();
		in.close();
		return super.SUCCESS;
	}	
}

利用工具类可以减少一些代码:

利用工具类就是一行代码,却替换掉了inputstream,outputstream写入写出以及关闭等等之类的代码

InputStream in = new FileInputStream(upload);
		
		OutputStream out = new FileOutputStream(realPath);
		
		int len = -1;
		
		byte [] bs = new byte[1024];
		
		while((len = in.read(bs) ) != -1 ){
			out.write(bs, 0, len);
		}
		
		out.close();
		in.close();
		
		/*
		 * 利用文件工具类来减少代码
		 */
		FileUtils.copyFile(upload, new File(realPath));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值