struts1 实现 文件上传

9 篇文章 0 订阅
2 篇文章 0 订阅

  今天帮师兄加了一个文件上传的功能,在网上找了找资料,struts1对文件上传支持的很好,用起来很方便,其中利用<html:file>可以很方便的上传文件

<html:file>的属性为org.apache.struts.upload.FormFile,很方便获得其输入流,供新手参考~~

在jsp页面中
<html:form enctype="multipart/form-data" action="upload.do?command=upfile">          
 <html:file property="uploadfile"/>          
 <html:submit value="上传"/>        
</html:form> 

在struts-config.xml中
<action path="/upload"
  name="uploadForm"
  type="com.env.business.actions.UploadAction"
  parameter="command"
/>

<form-bean name="uploadForm" type="com.env.business.forms.UploadForm"/>


在对应的Form中

package com.env.business.forms;
import java.io.File;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm {
 public FormFile getUploadfile() {
  return uploadfile;
 }
 public void setUploadfile(FormFile uploadfile) {
  this.uploadfile = uploadfile;
 }
 private FormFile uploadfile;
}


 

对应的Action类中

public class UploadAction extends DispatchAction {
 public ActionForward upfile(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
 throws Exception {
  response.setHeader("Pragma","No-cache");
  response.setHeader("Cache-Control","no-cache");
  response.setDateHeader("Expires", 0);
  UploadForm upForm = (UploadForm) form;
  PrintWriter out = null; 
  try {
   response.setCharacterEncoding("GBK");
   out = response.getWriter();
   saveFile(upForm.getUploadfile()); // 将上传文件保存到指写的路径(在web.xml中配置)                
   out.println("上传文件成功.");
  } catch (Exception e) {
   System.out.println(e.getMessage());
   return null;
  }
  return null;
 }
 /**
  * 向服务器写文件
  * @param formFile
  * @throws Exception
  */
 protected void saveFile(FormFile formFile) throws Exception{
  //路径
  String path="D:\\";
  //得到输入流
  InputStream in = formFile.getInputStream();
  //上传
  FileOutputStream fout = new FileOutputStream(path + formFile.getFileName());              
  byte buffer[] = new byte[8192];              
  int count = 0; 
  while ((count = in.read(buffer)) > 0){                 
   fout.write(buffer, 0, count);             
  } 
  fout.close();        //销毁当前文件     
  formFile.destroy();  
 }   
}


实现起来很方便,但是对大小以及断点续传功能没有做实现~~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值