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.jspuplod.jsp 注意关键字啊
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
文件上传功能