今天突然想研究下Struts的上传功能,没想到搞了两个小时才搞出来,卡在一个地方,总是报错说参数类型转化异常,结果我改动了下页面,却又神出鬼没的上传成功了,赶紧记录下
首先是web.xml中的配置,我个人喜欢每次弄个字符过滤器,以免出错
filter
com.wujintao.dao.SetCharacterEncodingFilter
encode
utf-8
filter
/*
action
org.apache.struts.action.ActionServlet
config
/WEB-INF/struts-config.xml
debug
2
detail
2
2
action
*.do
index.jsp
struts-config.xml中的配置,挺奇怪的最后两行必须得配上
name="uploadForm"
type="com.javacrazyer.web.action.UploadAction">
其次就是业务逻辑的代码了,在这之前我必须说下,这个Struts的上传用到的关键点就是自己自带的FormFile类了,因此在FormBean里面应该配上一个FormFile类型的属性
private String description; //文件的描述
private FormFile file; //文件具体内容对应的实例
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
业务逻辑处理代码
//具体业务流程处理方法,由Struts框架回调
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String toURL = "succ";
//取数据
UploadForm uForm = (UploadForm)form;
String desc = uForm.getDescription();
System.out.println("description==" + desc);
FormFile ff = uForm.getFile();
if(ff == null){
toURL = "fail";
return mapping.findForward(toURL);
}
System.out.println("文件名:" + ff.getFileName());
System.out.println("内容类型:" + ff.getContentType());
System.out.println("文件大小:" + ff.getFileSize() + "字节");
BufferedInputStream bis = new BufferedInputStream(ff.getInputStream());
//目标路径
String destPath = this.getServlet().getServletContext().getRealPath("/files");
System.out.println(destPath+"===============================");
BufferedOutputStream bos = null;
try{
bos = new BufferedOutputStream(new FileOutputStream(destPath + "/" + ff.getFileName()));
//从源文件中取数据,写到目标文件中
byte [] buff = new byte[8192];
for(int len = -1; (len = bis.read(buff)) != -1;){
bos.write(buff, 0, len);
}
bos.flush();
}catch(IOException ie){
ie.printStackTrace();
toURL = "fail";
}finally{
if(bis != null){
try{
bis.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
if(bos != null){
try{
bos.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
}
return mapping.findForward(toURL);
}
接下来我要说的,大家都猜到了肯定是JSP页面的上传表单了,这里就是卡住我的罪魁祸首
My JSP 'index.jsp' starting page为什么说它是罪魁祸首呢,因为一直都认为是最佳的上传表单,谁知道我找了大半天,竟然出现在这里的它必须是STRUTS标签的表单元素,郁闷!!!深刻的教训啊。
0
顶
0
踩
分享到:
2010-03-18 14:23
浏览 2047
评论