package upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class StrutsUpload extends ActionSupport{
/**
* struts2文件上传要点
* 1、首先从显示层开始,form表单中的enctype属性值必须是multipart/form-data ,method属性必须是post,上传控件name属性必须得指定一个值;
* 2、再看Action层,首先Action层用来接收前端页面传来的File对象的属性名必须要和上传控件的name属性相同,否则获取不到上传的File对象,若要获取到上传的
* 文件的原始文件名以及MIME类型,属性的命名格式必须得是“File属性名+FileName”或者“File属性名+ContentType”;
* 3、struts2文件上传的默认最大值为2M,修改默认最大值:<constant name="struts.multipart.maxSize" value="5000000"/>;
*
* 文件上传拦截器的作用
* 1、将表单中上传的文件,以临时文件的形式保存到服务器临时路径下;
* 2、将该临时文件对象注入Action;
* 3、删除临时文件;
*/
private File file;
private String fileFileName;
private String fileContentType;
public String upSingle(){
return SUCCESS;
}
public String upLoad(){
/**
* 要做的事:
* 1、判断文件大小;1M = 1024KB ,1KB = 1024B(字节)
* 2、判断文件的格式;
* 3、给文件重命名;
* 4、判断file非空;(可以在jsp中通过获取上传控件value属性来判断)
* 5、一般上传文件都在项目下创建文件夹存储;
*/
FileInputStream fis;
FileOutputStream fos;
try {
HttpServletRequest request = ServletActionContext.getRequest();
String rootPath = ServletActionContext.getServletContext().getRealPath("/upload");
File path = new File(rootPath);
if(!path.exists()){
path.mkdirs();
}
fis = new FileInputStream(file);
fos = new FileOutputStream(rootPath+File.separator+fileFileName);
byte[] data = new byte[1024];
int len =0;
while((len=fis.read(data)) != -1){
fos.write(data,0,data.length);
}
request.setAttribute("uploadMsg", "文件上传成功");
fis.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
}