UploadAction.java:
package crm.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File upload;
private String uploadFileName;
private String uploadContentType;
private String savePath;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getSavePath() {
//得到savePath的绝对路径
String filePath = ServletActionContext.getServletContext().getRealPath(savePath);
File saveFile = new File(filePath);
if(!saveFile.exists())
{
saveFile.mkdir();
}
return filePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String uploadFile()
{
try {
FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer=new byte[1024];
int len = 0;
while((len = fis.read(buffer))>0)
{
fos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
}
struts.xml:
/upload
/pages/file/upload.jsp
image/png,image/gif,image/pjpeg
20000
applicationContext.xml:
upload.jsp:
<%&#64; page language&#61;"java" import&#61;"java.util.*" pageEncoding&#61;"utf-8"%>
<%&#64; taglib prefix&#61;"s" uri&#61;"/struts-tags"%>
<%
String path &#61; request.getContextPath();
String basePath &#61; request.getScheme()&#43;"://"&#43;request.getServerName()&#43;":"&#43;request.getServerPort()&#43;path&#43;"/";
%>
文件&#xff1a;