struts文件上传 java_Struts中上传文件需要注意的地方

今天突然想研究下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

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2010-03-18 14:23

浏览 2047

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值