struts2实现文件上传

struts2实现文件上传


action部分:


package Action;

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

import javax.servlet.ServletOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class upload extends ActionSupport{

private File fexcel; //上传的文件;
private String fexcelFileName; //上传文件的文件名
private String fexcelContentType; //上传文件的文件的类型;
private String savePath; //文件保存的位置;

public File getFexcel() {
return fexcel;
}
public void setFexcel(File fexcel) {
this.fexcel = fexcel;
}
public String getFexcelFileName() {
return fexcelFileName;
}

public void setFexcelFileName(String fexcelFileName) {
this.fexcelFileName = fexcelFileName;
}
public String getFexcelContentType() {
return fexcelContentType;
}
public void setFexcelContentType(String fexcelContentType) {
this.fexcelContentType = fexcelContentType;
}

public String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String execute(){
FileOutputStream fos = null;
try {
fos = new FileOutputStream(this.getSavePath()+"\\"+this.fexcelFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();

}
FileInputStream fis;
try {
fis = new FileInputStream(this.getFexcel());
} catch (FileNotFoundException e) {
e.printStackTrace();
return "error";
}

byte [] buffer=new byte[1024];
int len=0;
try {
while((len=fis.read(buffer))>0){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
return "error";
}

return "success";
}
}



struts.xml部分:








error.jsp




application/vnd.ms-excel
20000000


/upload
/index.jsp
/upload.jsp
/upload.jsp




web.xml部分





xmlns="https://www.360docs.net/doc/9415162819.html,/xml/ns/javaee"
xmlns:xsi="https://www.360docs.net/doc/9415162819.html,/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.360docs.net/doc/9415162819.html,/xml/ns/javaee
https://www.360docs.net/doc/9415162819.html,/xml/ns/javaee/web-app_2_5.xsd">

index.jsp



struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter




contextConfigLocation
classpath:applicationContext.xml



struts2
/*



org.springframework.web.context.ContextLoaderListener





jsp页面部分:


<%@ taglib uri="/struts-tags" prefix="s" %>










jar包:

commons-fileupload-1.2.1.jar
commons-logging-1.0.4.jar
freemarker-2.3.15.jar
ognl-2.7.3.jar
struts2-core-2.1.8.jar
xwork-core-2.1.6.jar
commons-io-1.3.2.jar

相关文档
最新文档