转发自博客园Sunny的文章


1.以流的方式下载

public 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.addHeader("Content-Disposition", "attachment;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;
}

2.下载本地文件

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
// 下载本地文件
String fileName = "Operator.doc".toString(); // 文件的默认保存名
// 读到流中
InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
// 设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

3.下载网络文件

public void downloadNet(HttpServletResponse response) throws MalformedURLException {
// 下载网络文件
int bytesum = 0;
int byteread = 0; URL url = new URL("windine.blogdriver.com/logo.gif"); try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("c:/abc.gif"); byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

4.支持在线打开的方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0; response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

原博客评论 王洋(NREG)用户说:使用HttpServletResponse类,需要导入servlet-api.jar包,下载地址:https://pan.baidu.com/s/191RRRCFXWQOcT1zgpTyK5g 

提取码:2f3d

Java下载文件的几种方式的更多相关文章

  1. 【文件下载】Java下载文件的几种方式

    [文件下载]Java下载文件的几种方式  摘自:https://www.cnblogs.com/sunny3096/p/8204291.html 1.以流的方式下载. public HttpServl ...

  2. java 下载文件的两种方式和java文件的上传

    一:以网络的方式下载文件 try { // path是指欲下载的文件的路径. File file = new File(path); // 以流的形式下载文件. InputStream fis = n ...

  3. 从后端接口下载文件的2种方式:get方式、post方式

    从后端接口下载文件的2种方式 一.get方式 直接使用: location.href='http://www.xxx.com/getFile?params1=xxx&params2=xxxx' ...

  4. java 从网上下载文件的几种方式

    package com.github.pandafang.tool; import java.io.BufferedOutputStream; import java.io.File; import ...

  5. Java读写文件的几种方式

    自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...

  6. Asp.Net 下载文件的几种方式

    asp.net下载文件几种方式 protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法 ...

  7. php下载文件的一种方式

    <?php ob_start(); // $file_name="cookie.jpg"; $file_name="abc.jpg"; //用以解决中文不 ...

  8. asp.net 浏览器下载文件的四种方式

    // 方法一:TransmitFile实现下载 protected void Button1_Click(object sender, EventArgs e) { Response.ContentT ...

  9. C#从服务器下载文件的四种方式

    //方法一:TransmitFile实现下载 string fileName = "ss.docx"; //客户端预设的文件名,导出时可修改  string filePath = ...

随机推荐

  1. [Reinforcement Learning] 强化学习介绍

    随着AlphaGo和AlphaZero的出现,强化学习相关算法在这几年引起了学术界和工业界的重视.最近也翻了很多强化学习的资料,有时间了还是得自己动脑筋整理一下. 强化学习定义 先借用维基百科上对强化 ...

  2. P3203 [HNOI2010]弹飞绵羊

    LCT裸题,之后填坑打一下 分块做法:每个点存几次出块以及出块的位置,问的时候直接暴力跳就vans了 首先思考最普通的模拟,发现可以O(n)路径压缩,O(1)的查询,但是需要修改就变成了O(n^2)的 ...

  3. Dynamic Rankings

    板子题 用的整体二分 唯一要注意的是别总手误打错变量 最近总犯这样sb错误,我佛了 #include<bits/stdc++.h> using namespace std; const i ...

  4. kail linux虚拟机安装tools工具

    因为自己比较懒,有时候自己不想打字需要粘贴就安装了虚拟机tools工具,又因为自己脑子不好使所以就写一下步骤,以便以后用得着.我这里用得是kail linux系统,不知道contest能不能这样安,下 ...

  5. mysql远程连接很慢问题解决

    mysql开启远程访问发现从远程连接每次都在5秒以上,从本机连接很快. 解决方案: [mysqld] 标签下添加一行配置 skip-name-resolve 重启mysqld服务, 问题解决!

  6. js下载后台返回的docx(返回格式:文档流)文件

    原文地址: https://www.jianshu.com/p/a81c68c15fbd PS需要指定responseType类型,不然文件内容会乱码哦 咦?文件名乱码?需要手动设置文件名哦↓ 呀,文 ...

  7. 2018-2019-2 20165237《网络对抗技术》Exp2 后门原理与实践

    2018-2019-2 20165237<网络对抗技术>Exp2 后门原理与实践 一.实践目标 使用netcat获取主机操作Shell,cron启动 使用socat获取主机操作Shell, ...

  8. 论文翻译:Neural Networks With Few Multiplications

    目录 Abstract 1. Introduction 2.Related Work 3.Binary And Ternary Connect 3.1 BINARY CONNECT REVISITED ...

  9. iOS程序依赖管理的工具——CocoaPods

    1. 简介 CocoaPods是一个负责管理iOS项目中第三方开源代码的工具,其源码在Github上开源.使用CocoaPods可以节省设置和更新第三方开源库的时间并提高工作效率. 2. CocoaP ...

  10. 面向对象原生JavaScript案例炫彩小球

    面向对象其实对于初学者来说还是比较难以理解的,以前看到一个面试题目 面向对象是什么? 面向对象是一种思想,千万别入坑了: 这次给大家带来的是一个鼠标移动产生小球的案例,不是我不想给大家分享如何去认识面 ...