博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
经过证实的下载文件java实现方法
阅读量:6901 次
发布时间:2019-06-27

本文共 1769 字,大约阅读时间需要 5 分钟。

//会弹出对话框让用户自己选择保存路径
public static HttpServletResponse download(String path, HttpServletResponse response) {
     try {
         // path是指欲下载的文件的路径。
         File file = new File(path);
         // 取得文件名。
         String filename = file.getName();
         // 取得文件的后缀名。
         String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
         // 以流的形式下载文件。
         InputStream fis = new BufferedInputStream(new FileInputStream(path));
         byte[] buffer = new byte[fis.available()];
         fis.read(buffer);
         fis.close();
         // 清空response
         response.reset();
         // 设置response的Header
         //response.setHeader("Content-disposition","attachment;filename="+"book.zip");  
         response.addHeader("Content-Disposition", "inline;filename=" + new String(filename.getBytes()));
         response.addHeader("Content-Length", "" + file.length());
         OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
         
         response.setContentType("application/octet-stream");
         toClient.write(buffer);
         toClient.flush();
         toClient.close();
     } catch (IOException ex) {
         ex.printStackTrace();
     }
     return response;
 }
 //不会弹出保存对话筐
  public static void downloadNet(HttpServletResponse response,String desFilePath,String furl) throws MalformedURLException {
         // 下载网络文件
         int bytesum = 0;
         int byteread = 0;
         URL url = new URL(furl);
         try {
             URLConnection conn = url.openConnection();
             InputStream inStream = conn.getInputStream();
             FileOutputStream fs = new FileOutputStream(desFilePath);
             byte[] buffer = new byte[1204];
             int length;
             while ((byteread = inStream.read(buffer)) != -1) {
                 bytesum += byteread;
                 System.out.println(bytesum);
                 fs.write(buffer, 0, byteread);
             }
             fs.flush();//很重要
             fs.close();//很重要,否则下载的文件无法打开
             
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 
本文转自elbertchen 51CTO博客,原文链接:http://blog.51cto.com/linkyou/282612,如需转载请自行联系原作者
你可能感兴趣的文章
ToastUtil【简单的Toast封装类】【未自定义Toast的显示风格】
查看>>
新技术的学习
查看>>
架构师之路--谈业务的合理架构
查看>>
Apache + Tomcat 负载均衡 session复制
查看>>
暴力操作节点
查看>>
java多线程关键字volatile的使用
查看>>
Aptana下Django1.6以后的项目模板结构改造
查看>>
LoaderManager使用具体解释(四)---实例:AppListLoader
查看>>
软件系统的架构设计
查看>>
poj1159--Palindrome(dp:最长公共子序列变形 + 滚动数组)
查看>>
Codeforces #282 div 1 C Helping People 题解
查看>>
Java华氏转摄氏
查看>>
centos6.8服务器配置之编译安装PHP、配置nginx
查看>>
ddddddd
查看>>
Android 开发之 ---- 底层驱动开发(一)
查看>>
分享到朋友圈实现
查看>>
SQL Server 用链接服务器 同步SqlServer与MySQL
查看>>
Android程序的打包和安装
查看>>
Android内存优化6 了解Android是如何管理App内存
查看>>
SpringBoot2 添加应用拦截器
查看>>