`

下载文件

阅读更多
if("download".equals(ledgerForm.getAction())){//测试中
System.out.println("----------------download------------------");
String id=request.getParameter("id");
String realPath=this.getServlet().getServletContext().getRealPath("/");
if(realPath.endsWith("./")){//linux外网访问多了./ why???
realPath=realPath.substring(0, realPath.length()-2);
}
String uploadPath = realPath + "UserFiles"+File.separator+"Image"; //上传文件存放目录
String fileName = "E:\\TDDOWNLOAD\\fckedit.rar";//测试用例
try {
System.out.println("ContentType="+response.getContentType());
//     response.setContentType("application/rar");
response.setContentType("application/x-msdownload");
    response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
           
    File uploadFile = new File(fileName);
    FileInputStream fis = new FileInputStream(uploadFile);
    BufferedInputStream bis = new BufferedInputStream(fis);
    OutputStream fos = response.getOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    while ((bytesRead = bis.read(buffer)) != -1) {
        bos.write(buffer, 0, bytesRead);//将文件发送到客户端
    }
    bos.flush();
    fis.close();
    bis.close();
    fos.close();
    bos.close();
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   //e.printStackTrace();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   //e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   //e.printStackTrace();
  }finally{
  response.reset();
  }

  return null;
//initNewsList(mapping,ledgerForm,request,response);
//return mapping.findForward("management");
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics