一 前台jsp文件如下:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/WEB-INF/tld/struts-tags.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>文件上传</title>
</head>
<body>
<!-- 为了完成文件的上传,设置该表单的enctype属性为multipart/form-data -->
<s:form name="form1" action="uploadFile" method="post" enctype="multipart/form-data" >
<s:textfield name="title" label="文件标题"></s:textfield><br/>
<s:file name="upload" label="选择文件"></s:file>
<s:submit value="上传"></s:submit>
</s:form>
</body>
</html>
二 后台action处理如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String title;
private File upload;
private String uploadContentType;
private String uploadFileName;
private String savePath;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
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 getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String execute() throws Exception{
FileOutputStream fos = new FileOutputStream(this.getSavePath()+"//"+this.getUploadFileName());
FileInputStream fis = new FileInputStream(this.getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer))>0){
fos.write(buffer,0,len);
}
return SUCCESS;
}