用webwork的fileUploadInterceptor实现文件上传功能
1、upload.jsp
<ww:form name="form1" action="upload.action" method="post" enctype="multipart/form-data">
<ww:file name="file" label="picture"/>
<ww:submit />
</ww:form>
2、DocUpload.java
public class DocUpload extends ActionSupport {
//upload file
/*file可以任意命名,但是其他两个变量的命名规则是file+ContentType和
file+FileName,或者如果命名这里不注意,则在变量的setter和getter那里就要注意了,一定要是getFileFileName和getFileContentType*/
private String fileContentType; //文件的类型
private String fileFileName; //文件名
private File file; //文件
private User user;
public String uploadFile()
{
Map session=ActionContext.getContext().getSession();
if(session!=null)
user=(User)session.get("user");
upload();
System.out.println("caption="+fileFileName);
return SUCCESS;
}
//上传文件
private void upload()
{
if(file!=null)
{
FileOutputStream outputStream;
try {
ResourceBundle rb = ResourceBundle.getBundle("config");
String fileDir = rb.getString("saveDir")+user.getId()+File.separator;
String filePath=fileDir+fileFileName;
try{
//创建目录
File f=new File(fileDir);
f.mkdirs();
}catch(Exception e)
{
e.printStackTrace();
}
outputStream = new FileOutputStream(filePath);
FileInputStream fileIn = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fileIn.read(buffer)) > 0)
{
outputStream.write(buffer, 0, len);
}
fileIn.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("uploadfile name="+fileFileName);
}
else
{
System.out.println("file is null!");
}
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String contentType) {
this.fileContentType = contentType;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileName) {
this.fileFileName = fileName;
}
3、xwork.xml中的相关配置
<action name="upload" class="DocUpload" method="uploadFile">
<interceptor-ref name="fileUpload" />
<interceptor-ref name="defaultStack" /> <!-- must be defaultStack -->
<result name="success">/sys/uploadsuccess.jsp</result>
<result name="input">/sys/upload.jsp</result>
</action>
4、webwork.properties的相关配置
webwork.multipart.parser=jakarta
#file upload temp save
webwork.multipart.saveDir=d:/temp
其中,webwork.multipart.parser是设置处理上传的类的,有cos jakarta pell 三种设置, jakarta是默认的设置;注意设置了相应的类要把相应的jar放进来;
webwork.multipart.saveDir是设置临时保存文件的文件夹;
5、config.properties用来设置上传图片的保存路径,不是webwork上传功能必须的配置
#windows
saveDir=D:/Tomcat 5.5/webapps/pxbn/upload/
#linux
#saveDir=/home/web/tomcat/webapps/pxbn/upload/