Java下载文件的几种方式
转发自博客园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下载文件的几种方式的更多相关文章
- 【文件下载】Java下载文件的几种方式
[文件下载]Java下载文件的几种方式 摘自:https://www.cnblogs.com/sunny3096/p/8204291.html 1.以流的方式下载. public HttpServl ...
- java 下载文件的两种方式和java文件的上传
一:以网络的方式下载文件 try { // path是指欲下载的文件的路径. File file = new File(path); // 以流的形式下载文件. InputStream fis = n ...
- 从后端接口下载文件的2种方式:get方式、post方式
从后端接口下载文件的2种方式 一.get方式 直接使用: location.href='http://www.xxx.com/getFile?params1=xxx¶ms2=xxxx' ...
- java 从网上下载文件的几种方式
package com.github.pandafang.tool; import java.io.BufferedOutputStream; import java.io.File; import ...
- Java读写文件的几种方式
自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...
- Asp.Net 下载文件的几种方式
asp.net下载文件几种方式 protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法 ...
- php下载文件的一种方式
<?php ob_start(); // $file_name="cookie.jpg"; $file_name="abc.jpg"; //用以解决中文不 ...
- asp.net 浏览器下载文件的四种方式
// 方法一:TransmitFile实现下载 protected void Button1_Click(object sender, EventArgs e) { Response.ContentT ...
- C#从服务器下载文件的四种方式
//方法一:TransmitFile实现下载 string fileName = "ss.docx"; //客户端预设的文件名,导出时可修改 string filePath = ...
随机推荐
- CORS跨域 Ajax headers 问题
今天我们遇到了一个CORS跨域的问题Ajax如下 var url = "http://localhost:11980/api/Demo/GetString"; //api地址 $. ...
- python3 练手实例6 做一个简单日历
import calendar year = int(input('请输入要查询的年份:')) month = int (input('请输入要查询的月数:')) print (calendar.mo ...
- Timer定时方法(间隔时间后执行)
Timer time = new Timer(); time.schedule(new TimerTask() { @Override public void run() { // TODO Auto ...
- Ansible-----include
什么是include 在ansible中,我们可以通过include,在一个playbook中包含另一个文件,以便实现代码的重复利用. include_tasks模块 include_tasks模块用 ...
- vue 双向数据绑定的实现学习(二)- 监听器的实现
废话:上一篇https://www.cnblogs.com/adouwt/p/9928278.html 提到了vue实现的基本实现原理:Object.defineProperty() -数据劫持 和 ...
- nginx conf_ctx ****
http://blog.chinaunix.net/uid-27767798-id-3840094.html 断断续续看完了,还是没有全部清晰
- HTML5 移动端Meta设置
1. 强制让文档的宽度与设备的宽度保持1:1,并且文档最大的宽度比例是1.0,且不允许用户点击屏幕放大浏览. <meta name="viewport" content= ...
- 关于在eclipse中添加windowbuilder插件的问题
最近在学习GUI,发现我的Eclipse中没有windowbuilder插件,之后按照百度搜索,按照网上教程,去安装时,发现下载网页已经更新,造成了很多问题, 不过问题不大,我已经找到了解决方法: 安 ...
- 使用Open Live Write发布CSDN博客
---安装open live write 1.序 在CSDN上发布博客相当麻烦,图片一张张的上传确实让人头大,虽然通过office也能发布博客,不过Open Live Write软件使用感觉更好. 2 ...
- Scyther 论文相关资料整理
1.Scyther 的特点使用方法 Scyther可以提供轨迹的简单描述,方便分析协议可能出现的攻击和表现,使用Athena算法,该软件表现如下特点: 该软件有明确的终止,能工提供无限会话协议安全性的 ...