Struts 1 之文件上传

Struts 1 对Apache的commons-fileupload进行了再封装,把上传文件封装成FormFile对象

定义UploadForm:

private FormFilefile;       //上传的文件
private Stringtext;    //文件备注
//省略setter、getter
 

JSP:

<html:from action="/upload?method=upload" enctype="multipart/form-data">
 
文件:<html:file property="file"></html:file>
<br/>
备注:<html:textarea property="text"></html:textarea>
<br/>
<html:submit value=”开始上传”/>
 
</html:form>

 

处理上传操作的action:

 

UploadForm uploadForm = (UploadForm) form;
 
StringBuffer buffer = new StringBuffer();
 
if(uploadForm.getFile()!= null && uploadForm.getFile().getSize()>0){
      //获取文件夹/WEB-INF/classes
      File classes = new File(getClass().getClassLoader().getResource("").getFile());
     
      //获取文件夹/upload
      File uploadFolder = new File(classes.getParentFile().getParentFile(),"upload");
      uploadFolder.mkdirs();
 
      //保存到/upload文件夹下面
      File file = new File(uploadFolder, uploadForm.getFile().getFilename());
     
      OutputStreat ous = null;
      InputStream ins = null;
      try{
             byte [] byt = new byte [1024];
             int len = 0;
             ins =uploadForm.getFile().getInputStream();
             ous = new FileOutputStream(file);
             while((len = ins.read(byt))!=-1){
                    ous.write(byt,0,len);
             }
      }finally{
             ins.close();
             ous.close();
      }
      //点击即可下载
      buffer.append("文件:"+"<a href=upload/>"+file.getName()+"target=_blank>"+file.getName()+"</a><br/>");
}else{
      buffer.append("没有选择文件!<br/>");
}
buffer.append("备注:"+ uploadForm.getText()+"<br/>");
response.setCharacterEncoding("UTF-8");
response.getWriter().writer(buffer.toString());


转载于:https://www.cnblogs.com/duadu/p/6335846.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值