Java文件下载的几种方式

巧舌如簧
• 阅读 170

Java文件下载的几种方式

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;
}

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();
}
}

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();
}
}
//支持在线打开文件的一种方式
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  Java中文网:http://www.javaweb.cc
} 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();
}

点赞
收藏
评论区
推荐文章
Easter79 Easter79
3年前
vue+axios下载pdf文件流
项目中用到流文件下载的需求,之前使用的方法一直都没问题,但是这次就是下载不下来,查了多种方法终于解决了,方式如下://下载文件downLoadFile(e){letide.target.dataset.id;letnamee.target.dataset.name;
Wesley13 Wesley13
3年前
java下载文件指定目录下的文件
方法一:@RequestMapping('download')defdownload(HttpServletRequestrequest,HttpServletResponseresponse){TtxSessionsessiongetSession(request)StringfileName'OrderD
Easter79 Easter79
3年前
springmvc之下载文件
springMVC下载文件在开发web项目时,我们经常会遇到下载文件的情况。我们下来看下面这个代码:publicvoiddownLoad(HttpServletResponseresponse,Stringfilename){if(filenull||!file.exis
Wesley13 Wesley13
3年前
java代码跨域通用方法
/通用的跨越调接口方法@parampath请求的url路径@return/publicstaticStringgetHttpResponse(Stringpath){try{URLurlnewURL(path);HttpURLConnectionconn
Wesley13 Wesley13
3年前
java实现大文件下载(http方式)
java实现大文件下载,基于http方式,控件神马的就不说了。思路:下载文件无非要读取文件然后写文件,主要这两个步骤,主要难点:    1.读文件,就是硬盘到内存的过程,由于jdk内存限制,不能读的太大。    2.写文件,就是响应到浏览器端的过程,http协议是短链接,如果写文件太慢,时间过久,会造成浏览器死掉。知识点:
Wesley13 Wesley13
3年前
java文件下载
packagecom.common.util;importorg.apache.log4j.Logger;importjavax.servlet.http.HttpServletResponse;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;impo
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Stella981 Stella981
3年前
Mac上制作Ubuntu USB启动盘
Mac上制作UbuntuUSB启动盘一、下载ubuntuiso镜像二、将iso转换为img文件$hdiutilconvertformatUDRWo/path/to/generate/img/file/path/to/your/iso/file该命令会生成一个.img的磁盘镜像文件,但是macos
Stella981 Stella981
3年前
Gradle 任务访问文件的几种方式
例子:三种方式,使用taskfile{//relativepathFileconfigFilefile('build.gradle')println'relativepath:'configFile//Usinganabsolutepath
Stella981 Stella981
3年前
Post 方式进行文件下载
不啰嗦了,直接上代码,依赖jquery,下面代码可以直接复制到你的项目作为公共方法前端封装代码,作为公共方法://postDownload.js/下载文件,以POST的方式提交@paramoptions{url,data}使用方式postDownload({
Easter79 Easter79
3年前
SpringBoot读取Resource下文件的几种方式
最近在项目中涉及到Excle的导入功能,通常是我们定义完模板供用户下载,用户按照模板填写完后上传;这里待下载模板位置为resource/excelTemplate/test.xlsx,尝试了四种读取方式,并且测试了四种读取方式分别的windows开发环境下(IDE中)读取和生产环境(linux下jar包运行读取)。第一种:ClassPath