服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - JavaWeb文件下载功能实例代码

JavaWeb文件下载功能实例代码

2020-05-22 11:14sennhai Java教程

这篇文章主要为大家详细介绍了JavaWeb文件下载功能实例代码,代码简单实用,感兴趣的小伙伴们可以参考一下

在工作中遇到的一个下载文件的功能,自己将其抽取出来,代码简单,希望能帮到大家,好了,话不多说,上代码!

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public void downloadFile(File file, String downName, HttpServletRequest request, HttpServletResponse response) {
 OutputStream out = null;
 FileInputStream fin = null;
 BufferedInputStream bin = null;
 try {
  if (file.exists()) {
  String finalFileName = null;
  String agent = request.getHeader("User-Agent");
  boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
  if (isMSIE) {
   finalFileName = URLEncoder.encode(downName, "UTF8");
  } else {
   finalFileName = new String(downName.getBytes("UTF-8"), "ISO-8859-1");
  }
  response.setContentType("application/x-msdownload");
  response.setHeader("Content-Disposition", "attachment; filename=".concat(finalFileName));
  out = response.getOutputStream();
  fin = new FileInputStream(file);
  bin = new BufferedInputStream(fin);
  for (int data = bin.read(); data > -1; data = bin.read()) {
   out.write(data);
  }
  } else {
  }
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  try {
  if (bin != null)
   bin.close();
  if (fin != null)
   fin.close();
  if (out != null)
   out.close();
  } catch (Exception e2) {
  e2.printStackTrace();
  }
 }
 }

以上就是本文JavaWeb文件下载的代码,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐