简单单个文件上传下载

最简单的上传下载,整理一下,以后用着方便

上传:

前端界面             ( type = "file"是用来选择文件)

<form action="infopbl/DocInfopbl_addTswj" method="post" name="addTswjForm"; οnsubmit="return check2()"  enctype="multipart/form-data">
         
           请选择文档:
          <input class="xzwd" id="word" name="tswj.wjmc"  type="file" value="浏览">
         <input type="submit" value="提交">&nbsp;&nbsp;&nbsp;&nbsp;
         <input id="reset" type="button" value="重置">
 </form>

 

后台程序处理

File fileIn = new File(saveName);                                           //savename为临时文件路径,是前台选择文件的name值(tswj.wjmc)
     String tomcat = ServletActionContext.getServletContext().getRealPath("/upload");
     String yafile = tomcat+"\\"+lj;

  File fileOut = new File(yafile);                                             //yafile为文件需要上传到的路径
  FileInputStream fis = new FileInputStream(fileIn);
  FileOutputStream fos = new FileOutputStream(fileOut);
  BufferedInputStream bis = new BufferedInputStream(fis);
  BufferedOutputStream bos = new BufferedOutputStream(fos);
  byte[] b = new byte[(int) fileIn.length()];                             //注意此处长度定义,按照文件大小定义,能够好的保证文件完整性
  int len = 0;
  if((len = bis.read(b)) != -1) {
   bos.write(b, 0, len);
  }
  fis.close();
  fos.close();

 

下载:

 

String wjmc = tswj.getWjmc();
//  String wjmc = "ceshi.xls";
  try{
   response.setCharacterEncoding("utf-8");
   response.setHeader("Content-Disposition", "attachment;filename="
     + new String((wjmc).getBytes(),"ISO-8859-1"));// 设定输出文件头
   response.setContentType("multipart/form-data");// 定义输出类型为所有
   OutputStream os = response.getOutputStream();
   File file = new File(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+wjmc);
   InputStream inputStream = new FileInputStream(file);
   //写文件  
   byte[] b = new byte[(int)file.length()];
   int len = 0;
   if((len = inputStream.read(b))>0) {
    os.write(b,0,len);
   }
     //关闭输出流  
     os.close(); 
     inputStream.close();
  }catch(Exception e){
   e.printStackTrace();
  }

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值