当前位置: 首页 > news >正文

java下载网络文件

/*** 下载文件** @param fileId* @param response* @throws Exception*/
@GetMapping("/downLoadFile")
public void downLoadFile(Long fileId, HttpServletResponse response) throws Exception{// 根据文件ID查询文件路径FileDO fileDO = fileService.get(fileId);// 定义一个URL对象,就是你想下载的图片的URL地址URL url = new URL(fileDO.getUrl());// 打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 设置请求方式为"GET"conn.setRequestMethod("GET");// 超时响应时间为10秒conn.setConnectTimeout(10 * 1000);// 通过输入流获取图片数据InputStream is = conn.getInputStream();// 得到图片的二进制数据,以二进制封装得到数据,具有通用性byte[] data = readInputStream(is);// 创建一个文件对象用来保存图片String[] filePathArr = fileDO.getPath().split("\\/");String fileUrl = rootUrl+"/"+filePathArr[filePathArr.length-1];File imageFile = new File(fileUrl);// 创建输出流FileOutputStream outStream = new FileOutputStream(imageFile);// 写入数据outStream.write(data);// 关闭输出流,释放资源outStream.close();BufferedInputStream bins = new BufferedInputStream(new FileInputStream(imageFile));response.setCharacterEncoding("UTF-8");response.setHeader("content-Type", "application/x-download");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(imageFile.getName(), "UTF-8"));ServletOutputStream out = null;try {// 这边直接在浏览器下载out = response.getOutputStream();int bytesRead = 0;byte[] buffer = new byte[8192];while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {out.write(buffer, 0, bytesRead);}out.flush();bins.close();out.close();FileUtil.deleteFile(fileUrl);// 删除文件} catch (IOException e) {e.printStackTrace();}
}
public static byte[] readInputStream(InputStream inStream) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream();// 创建一个Buffer字符串byte[] buffer = new byte[6024];// 每次读取的字符串长度,如果为-1,代表全部读取完毕int len;// 使用一个输入流从buffer里把数据读取出来while ((len = inStream.read(buffer)) != -1) {// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度outStream.write(buffer, 0, len);}// 关闭输入流inStream.close();// 把outStream里的数据写入内存return outStream.toByteArray();
}
http://www.lryc.cn/news/293027.html

相关文章:

  • 大数据信用报告查询费用一般要多少钱?
  • 【操作宝典】IntelliJ IDEA新建maven项目详细教程
  • 【Java程序设计】【C00196】基于(JavaWeb+SSM)的旅游管理系统(论文+PPT)
  • pdmodel从动态模型转成静态onnx
  • git 如何修改仓库地址
  • 基于springboot篮球论坛系统源码和论文
  • 【三维重建】运动恢复结构(SfM)
  • Android Studio非UI线程修改控件——定时器软件
  • canvas的一些基础
  • C++(10)——类与对象(最终篇)
  • NetApp FAS2750 和 FAS2820 简化分布式企业的存储
  • Geogebra设置函数定义域
  • 代码随想录刷题笔记 DAY 18 | 找树左下角的值 No.513 | 路经总和 No.112 | 从中序与后序遍历序列构造二叉树 No.106
  • 【algorithm】一个简单的PID工程 base 用于手生时候快速复习 用于设计模式 cpp语法八股 快速复习校验
  • Python处理图片生成天际线(2024.1.29)
  • jsp服装穿搭推荐系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • Opencv(C++)学习 之RV1126平台的OPENCV交叉编译
  • http和https区别
  • 富文本编辑器CKEditor4简单使用-05(开发自定义插件入门)
  • chisel之scala 语法
  • React18构建Vite+Electron项目以及打包
  • Spark性能调优
  • flutter开发实战-Camera自定义相机拍照功能实现
  • LeetCode15. 三数之和
  • Docker搭建MySQL8主从复制
  • 【前端】日期转换
  • Git 怎么设置用户的权限
  • 大端和小端模式介绍
  • 【vue】报错 Duplicate keys detected 解决方案
  • 机器学习_13_SVM支持向量机、感知器模型