Struts2上传拦截处理

package cn.bdqn.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {
private File upload;
private String uploadContentType; //文件类型
private String uploadFileName; //文件名称

private String name;	//上传人

public String upload(){
	//方法二:
	//获取指定目录的绝对路径
	String path = ServletActionContext.getServletContext().getRealPath("uploads/");
	//创建目录对象
	File parent = new File(path);
	//判断目录是否存在
	if(!parent.exists()){
		//目录不存在,创建目录
		parent.mkdirs();
	}
	try {
		//使用Commons-io API
		FileUtils.copyFile(getUpload(), new File(parent,getUploadFileName()));
	} catch (IOException e) {
		e.printStackTrace();
	}
	return SUCCESS;
}
public String upload000(){
	try {
		//方法一:使用文件复制
		//创建输入流对象
		FileInputStream fis = new FileInputStream(getUpload());
		//获取指定目录的绝对路径
		String path = ServletActionContext.getServletContext().getRealPath("uploads/");
		//创建输出流对象
		FileOutputStream fos = new FileOutputStream(path+getUploadFileName());
		//从输入流中读取内容  写入到输出流中
		byte[] buffer = new byte[1024];//缓冲器
		int len = -1;
		while((len=fis.read(buffer))!=-1){//读取内容到字节数组中,如果len=-1说明读取文件结束
			//将字节数组中的内容写入到文件中
			fos.write(buffer, 0, len);
		}
		//关闭流
		fos.close();
		fis.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	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 getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}

}

Struts2.xml

<?xml version="1.0" encoding="UTF-8" ?> /index.jsp

uplod.jsp 注意关键字啊

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here

文件上传功能

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值