1.struts中的文件上传(struts.xml)
新建一个jsp页面:代码如下:
<form action="<%=basePath%>authority/upload" method="post" enctype="multipart/form-data">
选择你要上传的文件:<input type="file" name="file"/>
<input type="submit" value="提交">
</form>
!!!!!!!!!!!!!!这里的method必须位post;enctype="multipart/form-data",并且上传控件必须有name属性;
2.后台建一个action接收,:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File file; //与上传input控件的name相同
private String fileFileName; //名字的确定是有上传的控件input的name属性确定,
private String fileContentType;
/**
* @return the file
*/
public File getFile() {
return file;
}
/**
* @param file the file to set
*/
public void setFile(File file) {
this.file = file;
}
/**
* @return the fileFileName
*/
public String getFileFileName() {
return fileFileName;
}
/**
* @param fileFileName the fileFileName to set
*/
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
/**
* @return the fileContentType
*/
public String getFileContentType() {
return fileContentType;
}
/**
* @param fileContentType the fileContentType to set
*/
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
/* (non-Javadoc)
* @see com.opensymphony.xwork2.ActionSupport#execute()
*/
@Override
public String execute() throws Exception {
System.out.println(file);
System.out.println(fileFileName);
System.out.println(fileContentType);
System.out.println(file);
System.out.println(ServletActionContext.getServletContext().getRealPath("fileupload"));
//用io流来保存文件,ServletActionContext.getServletContext().getRealPath("fileupload\\"+fileFileName)可以定位到你的项目的WebRoot下的fileuoload文件下;
BufferedOutputStream bo=new BufferedOutputStream(new FileOutputStream(ServletActionContext.getServletContext().getRealPath("fileupload\\"+fileFileName)));
BufferedInputStream bs=new BufferedInputStream(new FileInputStream(file));
byte[] buf=new byte[1024];
int len=-1;
while(-1!=(len=bs.read(buf))){
bo.write(buf,0,len);
}
bo.flush();
bo.close();
bs.close();
return null;
}
}
!!!!!!!!!!!!!!此action 中的成员变量File file 必须为前台jsp对应控件的name属性XXX,XXXFileName;XXXContentType