转发自博客园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. clickhouse修改时区

    clickhouse时区设置 sudo vim /etc/clickhouse-server/config.xml <timezone>Asia/Shanghai</timezone ...

  2. Html.ActionLink与Url.Action区别

    一.@Html.ActionLink()概述 在MVC的Rasor视图引擎中,微软采用一种全新的方式来表示从前的超链接方式,它代替了从前的繁杂的超链接标签,让代码看起来更加简洁.通过浏览器依然会解析成 ...

  3. 作业二Wordcount

    1,github地址 https://github.com/dtneverdie/word-count 2,PSP表格 3,解题思路 先从理论上判断应该先将文件内的字符全部读入,然后根据分隔符来进行单 ...

  4. 浅入深出Vue系列

    浅入深出Vue导航 导航帖,直接点击标题即可. 文中所有涉及到的资源链接均在最下方列举出来了. 前言 基础篇 浅入深出Vue:工具准备之WebStorm搭建及配置 浅入深出Vue之工具准备(二):Po ...

  5. 初识Asp.Net WebApi

    using System;using System.Collections.Generic;using System.Linq;using System.Net.Http;using System.T ...

  6. L1-Day12

    1.凡是杀不死你的都会让你变得更强.(什么关系?主语是什么?)[我的翻译]There is no killing you makes you stronger.[标准答案]What doesn’t k ...

  7. webpack4.0学习记录

    2019/04/28 1.本质上,webpack基于node  node跟webpack为最新稳定版,才能更好,更快的打包 安装 1.卸载node  直接在控制面板  卸载 2.安装 从官网下载 然后 ...

  8. EASY-X

    ----------------------- Page 1----------------------- 一 创建新项目 VC 写程序要有项目的概念,一个项目可以有多个 .cpp 文件,多个项目构 ...

  9. python正则表达式--findall、finditer方法

    findall方法 相比其他方法,findall方法有些特殊.它的作用是查找字符串中所有能匹配的字符串,并以结果存于列表中,然后返回该列表 注意: match 和 search 是匹配一次 finda ...

  10. ios手机访问H5页面中$(document).on绑定无效问题

    1.问题描述 用amazeUI做了个手机端网站,网站头部是一个点击按钮下拉菜单,点击页面其余区域下拉菜单隐藏.在chrome模拟安卓和iOS都可以正常触发,但是在真机实测的时候,iOS上面失效了.简单 ...