`
zengshaotao
  • 浏览: 764390 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

文件下载

    博客分类:
  • java
 
阅读更多

下载文件,就是将存储与服务器端的文件以流的形式发送到客户端,然后由客户端根据服务端的header内容,调用本地的mime插件,进行流的解析,最终解析成可读的文件形式:

 

String downloadDir = "";//可通过配置文件的形式获得 ,一般格式 /load/....

String filePath = request.getSession().getServletContext().getRealPath(File.separator);

 

if(filePath.endsWith(File.separator)){

      filePath = filePath.substring(0,filePath.length()-1);

}

 

filePath = filePath + downloadDir;

 

String displayName = ''displayFileName.xlsx";

response.setContentType("application/vnd.ms-excel");

response.addHeader("Content-disposition","attachment;filename="+displayName);

 

byte [] buffer = new byte[4096];

 

BufferedInputStream input = null;

BufferedOutputStream output = null;

 

try{

    input = new BufferedInputStream(new FileInputStream(new File(filePath)));

    output = new BufferedOutputStream(response.getOutputStream());

    int n=-1;

    while((n=input.read(buffer,0,buffer.length))>-1){

          output.write(buffer,0,n);

    }

    output.flush();

    response.flushBuffer();

}catch(Exception e){

    e.printStackTrace();

}finally{

      关闭流

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics