Java文件下載代碼

public  static  void DownLoadFile (String filePath, String fileName,
                  HttpServletResponse response)  throws  Exception {
            System. out .println( "filepath:"  + filePath);
            File file =  new  File(filePath);
             if  (!file.exists()) {
                  System. out .println( "文件不存在" );
            }  else  {
                  FileInputStream fis =  new  FileInputStream(file);
                  BufferedInputStream bis =  new  BufferedInputStream(fis);
 
                  OutputStream os = response.getOutputStream();
                  BufferedOutputStream bos =  new  BufferedOutputStream(os);
 
                  fileName = URLEncoder.encode(fileName,  "UTF-8" );
                  fileName =  new  String(fileName.getBytes( "UTF-8" ),  "GBK" );
 
                  response.reset();
                  response.setContentType( "UTF-8" );
                  response.setContentType( "Application/x-msdownload" );
                  response.setHeader( "Content-Disposition" ,  "attachment;filename="
                              + fileName);
                  response.setHeader( "Content-Length" , String
                              .valueOf(bis.available()));
 
                   int  bytesRead = 0;
                   byte [] buffer =  new  byte [1024];
                   while  ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);
                  }
                  bos.flush();
                  bos.close();
                  bis.close();
 
                  os.close();
                  fis.close();
            }
      }
相關文章
相關標籤/搜索