下載(導出)文件,如視頻、Excel、word文件等

1.前臺發送請求
//下載模版  jQuery 中的方法
function _uploadModel(){
         window.location =  "${basePath}docAndInfra/uploadModel.do";
}

2.後臺接收請求

/**
  * 下載excel表格的模版
  * @param request
  * @param response
@Constants.DOCANDINFRA_EXPORTEXCEL  是Excel表格模版在FTP上 的下載地址
  * @throws Exception
  */
 @RequestMapping("uploadModel.do")
 public void uploadModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
              String fileName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Excel模版"+".zip";
              queryAndUseService.upLoadInfo(Constants.DOCANDINFRA_EXPORTEXCEL,fileName,request,response);
 }

3、server 成處理請求

/**
  * 下載附件
  * @param accessoryInfo
  * @param fileName
  * @param request
  * @param response
  * @throws Exception
  */
 @Transactional
 public void upLoadInfo(String accessoryInfo,String fileName,HttpServletRequest request,HttpServletResponse response)throws Exception{
  Path ftpPath = null;
  FTPClient ftp = null;
  // 設置消息頭
  String contentType = "application/octet-stream";
  response.setContentType("text/html;charset=UTF-8");
  response.setContentType(contentType);
  request.setCharacterEncoding("UTF-8");
  response.setHeader("Content-disposition", "attachment; filename="
    + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
  BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
  ZipOutputStream zos = new ZipOutputStream(bos);
  // 設置流編碼方式
  zos.setEncoding("utf-8");
  String filePath =accessoryInfo.replace("\\", "/");
  String ftpPathCode = filePath.substring(0, filePath.indexOf("/"));
  ftpPath = Constants.initPathMap.get(ftpPathCode);
  StringBuffer fileNames=new StringBuffer();
  fileNames.append("下載文件").append("\\");
  if(ftpPath!=null){
   ftp= FTPUtils.getFtpClient(ftpPath.getServerPath(), ftpPath.getPort(), ftpPath.getUsername(), ftpPath.getPassword());
   ftp.enterLocalPassiveMode();
   String rootPath=accessoryInfo.substring(filePath.indexOf("/")+1);
   Boolean flag=ftp.changeWorkingDirectory(rootPath);
   if(flag){
    FTPFile[] list = ftp.listFiles();
    Integer listCount=list.length;
    for(int i=0;i<listCount;i++){
     FTPFile f=list[i];
     //在火狐瀏覽器上處理文件名亂碼的問題
     zos.putNextEntry(new ZipEntry(fileNames.toString() + new String(f.getName().getBytes("iso8859-1"), "GBK"))); 
     ftp.retrieveFile(f.getName(), zos);
     zos.closeEntry();
    }
   }else{
    zos.putNextEntry(new ZipEntry(fileNames.toString() + "文件不存在"));
    ftp.retrieveFile("文件不存在", zos);
    zos.closeEntry();
   }
   
  }
  zos.close();
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章