栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb文件下载功能实例代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb文件下载功能实例代码

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

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文件下载的代码,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/149707.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号