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

Java文件前后端上传下载工具类

  1. 任何非压缩格式下载
package com.pisx.pd.eco.util;import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.multipart.MultipartFile;import com.pisx.pd.commom.utils.FileSizeUnitTransform;
import com.pisx.pd.eco.config.FilePathConfig;import lombok.extern.slf4j.Slf4j;@Slf4j
public class FileUtils {public static String downloadFile(HttpServletResponse response, String fileName, String filePath) {InputStream inStream = null;FileInputStream fis = null;ServletOutputStream servletOs = null;try {// 文件path路径File file = new File(filePath, fileName);if (file.exists()) {response.reset();response.setContentType("application/x-msdownload");response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");int fileLength = (int)file.length();response.setContentLength(fileLength);/* 如果文件长度大于0 */if (fileLength != 0) {/* 创建输入流 */fis = new FileInputStream(file);inStream = new BufferedInputStream(fis);byte[] buf = new byte[4096];/* 创建输出流 */servletOs = response.getOutputStream();int readLength;while (((readLength = inStream.read(buf)) != -1)) {servletOs.write(buf, 0, readLength);}}return "下载成功";} else {return "文件不存在";}} catch (Exception e) {e.printStackTrace();return "下载文件出错";} finally {if (inStream != null) {try {fis.close();inStream.close();} catch (IOException e) {log.info(e.getMessage());}}if (servletOs != null) {try {servletOs.flush();servletOs.close();} catch (IOException e) {log.info(e.getMessage());}}}}public static String downloadFile(HttpServletResponse response, InputStream inputStream, String fileName) {ServletOutputStream servletOs = null;try {response.reset();response.setContentType("application/x-msdownload");response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");byte[] buf = new byte[4096];/* 创建输出流 */servletOs = response.getOutputStream();int readLength;while (((readLength = inputStream.read(buf)) != -1)) {servletOs.write(buf, 0, readLength);}return "下载成功";} catch (Exception e) {e.printStackTrace();return "下载文件出错";} finally {if (servletOs != null) {try {servletOs.flush();servletOs.close();} catch (IOException e) {log.info(e.getMessage());}}}}public static Map<String, String> uploadFile(MultipartFile file, String filePath, String fileName) {String fileUrl = filePath + fileName;// 获取文件大小String fileSize = FileSizeUnitTransform.GetFileSize(file.getSize());// 获取文件类型int index = fileName.lastIndexOf(".");// 文件格式类型String fileFormat = fileName.substring(index + 1);// 把文件以指定的名字写入指定的路径中File filed = new File(FilePathConfig.PATH + fileUrl);if (!filed.getParentFile().exists()) {boolean mkdirs = filed.getParentFile().mkdirs();if (Boolean.FALSE.equals(mkdirs)) {return Collections.emptyMap();}}try {file.transferTo(filed);} catch (Exception ex) {log.error(ex.getMessage());}Map<String, String> map = new HashMap<>(3);map.put("fileUrl", fileUrl);map.put("fileSize", fileSize);map.put("fileFormat", fileFormat);return map;}private FileUtils() {throw new IllegalStateException("Utility class");}
}
  1. 压缩包格式下载
package com.pisx.pd.eco.util;import com.pisx.pd.commom.utils.FileSizeUnitTransform;
import com.pisx.pd.datasource.lib.entity.eco.CarbonMore;
import com.pisx.pd.datasource.lib.entity.eco.MineFileDto;
import com.pisx.pd.datasource.lib.entity.eco.StatementTemplate;
import com.pisx.pd.eco.config.FilePathConfig;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;public class UploadFileUtil {static class FileContent {// 文件存储路径String fileUrl = null;// 文件真实名称String fileName = null;// 文件全路径String filePath = null;// 获取文件大小String fileSize = null;// 获取文件类型String fileFormat = null;public String getFileUrl() {return fileUrl;}public void setFileUrl(String fileUrl) {this.fileUrl = fileUrl;}public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public String getFilePath() {return filePath;}public void setFilePath(String filePath) {this.filePath = filePath;}public String getFileSize() {return fileSize;}public void setFileSize(String fileSize) {this.fileSize = fileSize;}public String getFileFormat() {return fileFormat;}public void setFileFormat(String fileFormat) {this.fileFormat = fileFormat;}public void setExceptFileFormatName(String substring) {}}public static List<FileContent> uploadFileUtil(MultipartFile[] files, String fileUrl) {if (files != null && files.length > 0) {try {List<FileContent> list = new ArrayList<>();for (MultipartFile item : files) {FileContent f = new FileContent();// 文件真实名称f.setFileName(item.getOriginalFilename());// 获取文件大小f.setFileSize(FileSizeUnitTransform.GetFileSize(item.getSize()));// 获取文件类型int index = item.getOriginalFilename().lastIndexOf(".");// 除过文件格式名称f.setExceptFileFormatName(item.getOriginalFilename().substring(0, index));// 文件格式类型f.setFileName(item.getOriginalFilename().substring(index + 1));f.setFileUrl(fileUrl);f.setFilePath(fileUrl + item.getOriginalFilename());list.add(f);// 把文件以指定的名字写入指定的路径中File file = new File(fileUrl + item.getOriginalFilename());if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}}return list;} catch (Exception e) {e.printStackTrace();}}return null;}// 文档下载方法调用的三个静态方法public static byte[] getPackage(MineFileDto file) {byte[] bag = null;try {String filePath = file.getFile_path();bag = getBytesByFile(filePath);} catch (Exception e) {e.printStackTrace();}return bag;}// 文档下载方法调用的三个静态方法public static byte[] getPackageCarbonMore(CarbonMore file) {byte[] bag = null;try {String filePath = file.getFile_path();bag = getBytesByFile(filePath);} catch (Exception e) {e.printStackTrace();}return bag;}// 文档下载方法调用的三个静态方法public static byte[] getPackages(String filePath) {byte[] bag = null;try {bag = getBytesByFile(filePath);} catch (Exception e) {e.printStackTrace();}return bag;}@Nullableprivate static byte[] getBytesByFile(String filePath) {try {File file = new File(FilePathConfig.PATH + filePath);// 获取输入流FileInputStream fis = new FileInputStream(file);// 新的 byte 数组输出流,缓冲区容量1024byteByteArrayOutputStream bos = new ByteArrayOutputStream(1024);// 缓存byte[] b = new byte[1024];int n;while ((n = fis.read(b)) != -1) {bos.write(b, 0, n);}fis.close();// 改变为byte[]byte[] data = bos.toByteArray();bos.close();return data;} catch (Exception e) {e.printStackTrace();}return null;}public static void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName) {try {response.setContentType("application/x-msdownload");response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());BufferedOutputStream bos = new BufferedOutputStream(zos);for (Map.Entry<String, byte[]> entry : files.entrySet()) {// 每个zip文件名String fileName = entry.getKey();// 这个zip文件的字节byte[] file = entry.getValue();BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));zos.putNextEntry(new ZipEntry(fileName));int len = 0;byte[] buf = new byte[10 * 1024];while ((len = bis.read(buf, 0, buf.length)) != -1) {bos.write(buf, 0, len);}bis.close();bos.flush();}bos.close();} catch (Exception e) {e.printStackTrace();}}
}

相关文章:

Java文件前后端上传下载工具类

任何非压缩格式下载 package com.pisx.pd.eco.util;import java.io.*; import java.util.Collections; import java.util.HashMap; import java.util.Map;import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse;import org.springframewo…...

内燃机可变气门驱动研究进展

Review of Advancement in Variable Valve Actuation of Internal Combustion Engines AbstractIntroduction燃烧和气体交换需要电子控制 paper Abstract 近年来&#xff0c;人们对空气污染和能源使用的日益关注导致了车辆动力总成系统的电气化。 另一方面&#xff0c;一个多世…...

NEFU离散数学实验2-容斥原理

相关概念 离散数学中的容斥原理是一种使用集合运算的技巧&#xff0c;通常用于计算两个或更多集合的并集或交集的大小。以下是一些与容斥原理相关的常见概念和公式。 概念&#xff1a; 1. 集合&#xff1a;由元素组成的对象&#xff0c;通常用大写字母表示&#xff0c;如A、B、…...

解决Windows内存溢出/占满死机问题-PoolMon工具

某一天&#xff0c; 工作所用笔记本突然越来越卡直至死机 以为只是windows11的抽风行为&#xff0c;之前就因为windows11资源管理器经常卡死&#xff08;后升级小版本好多了&#xff09;。 遂长按电源键强制关机重启。 然慢慢又越来越卡&#xff0c;直至卡死&#xff0c;无…...

【ROS】ros-noetic和anaconda联合使用【教程】

【ROS】ros-noetic和anaconda联合使用【教程】 文章目录 【ROS】ros-noetic和anaconda联合使用【教程】1. 安装anaconda2. 创建虚拟环境3. 查看python解释器路径4. 在虚拟环境中使用任意的包5. 创建工作空间和ros功能包进行测试Reference 1. 安装anaconda 在Ubuntu20.04中安装…...

自动化RPA开发 --获取所有窗口信息和进程信息

场景 准备做一个RPA工具&#xff0c;可以从桌面和浏览器选择元素&#xff0c;获取窗口信息和进程信息是必要的&#xff0c;因为获取了窗口信息和进程&#xff0c;可用对程序做一些想要的操作。 coding 工具类 /*** Windows系统工具类*/ public class WinOsUtils {static fi…...

【Qt之布局】QVBoxLayout、QHBoxLayout、QGridLayout、QFormLayout介绍及使用

在Qt中&#xff0c;布局管理器&#xff08;Layout&#xff09;用于管理窗口中的控件的位置和大小&#xff0c;以适应不同大小的窗口。 常用的布局管理器包括QVBoxLayout、QHBoxLayout、QGridLayout和QFormLayout。 先放张布局UI&#xff1a; 1. QVBoxLayout&#xff08;垂直布…...

【计算机毕业设计】python在线课程培训学习考试系统637r7-PyCharm项目

使用说明 使用Navicat或者其它工具&#xff0c;在mysql中创建对应名称的数据库&#xff0c;并导入项目的sql文件&#xff1b; 使用PyCharm 导入项目&#xff0c;修改配置&#xff0c;运行项目&#xff1b; 将项目中config.ini配置文件中的数据库配置改为自己的配置&#xff0c;…...

vue3后台管理系统之登录界面和业务的实现

1.静态页面的搭建 <template><div class"login_container"><el-row><el-col :span"12" :xs"0" /><el-col :span"12" :xs"24"><!-- 登录的表单 --><el-form ref"loginForms&qu…...

GEE19:基于Landsat8的常见的植被指数逐年获取

植被指数逐年获取 1. 常见的植被指数1.1 比值植被指数&#xff08;Ratio vegetation index&#xff0c;RVI&#xff09;1.2 归一化植被指数&#xff08;Normalized Difference Vegetation Index&#xff0c;NDVI&#xff09;1.3 增强植被指数&#xff08;Enhanced Vegetation I…...

Python【多分支实际应用的练习】

要求:某商店T恤的价格为35元/件&#xff08;2件9折&#xff0c;3件以上8折&#xff09;,裤子的价格为120 元/条&#xff08;2条以上9折&#xff09;小明在该店买了3件T恤和2条裤子,请计算并显示小明应该付多少钱? 代码如下&#xff1a; tshirt_price 35 # T恤的单价 pan…...

LeetCode 343. 整数拆分(动态规划)

LeetCode 343. 整数拆分 思路&#xff1a; 通过题目我们可以知道&#xff0c;一个正整数最少拆成2个数&#xff0c;最多拆成n个数&#xff0c;即可拆分的个数为2&#xff5e;n 若将拆除的第一个正整数令为k&#xff0c;那么剩下的数则为n-k&#xff0c;此时可以不拆分&#x…...

C++对象模型(12)-- 构造函数语义学:构造函数

1、默认构造函数生成规则 编译器不一定会为类生成默认构造函数&#xff0c;但在下列情况下&#xff0c;编译器会生成默认构造函数。 &#xff08;1&#xff09;该类没有任何构造函数&#xff0c;但包含一个类类型的成员变量&#xff0c;且成员变量所属的类有默认构造函数。 …...

[23] T^3Bench: Benchmarking Current Progress in Text-to-3D Generation

3D生成蓬勃发展&#xff0c;主流方法通过事例比较和用户调查来评价方法好坏&#xff0c;缺少客观比较指标&#xff1b;本文提出Bench&#xff0c;首次综合比较了不同生成方法&#xff1b;具体来说&#xff0c;本文设计了质量评估&#xff08;Quality Assessment&#xff09;和对…...

linux系统如何定时关机

立刻关机 poweroff 10分钟后自动关机 shutdown -h 10 如果希望终止上面执行的10分钟关机&#xff0c;则执行&#xff1a; shutdown -c 希望在22:00关闭计算机 shutdown -h 22:00...

构建高性能物联网数据平台:EMQX和CnosDB的完整教程

CnosDB 是一款高性能、高压缩率、高易用性的开源分布式时序数据库。主要应用场景为物联网、工业互联网、车联网和IT运维。所有代码均已在GitHub开源。本文将介绍如何使用EMQX 这一MQTT 服务器 CnosDB 构建物联网数据平台&#xff0c;实现物联网数据的实时流处理。 前言 在物联…...

【vim 学习系列文章 11 -- vim filetype | execute | runtimepath 详细介绍】

文章目录 filetype plugin indent on 什么功能&#xff1f;vim runtimepath 详细介绍vim 中 execute 命令详细介绍execute pathogen#infect() 详细介绍 filetype plugin indent on 什么功能&#xff1f; 在网上我们经常可以看到vimrc配置中有 filetype plugin indent on 这个配…...

[备忘]WindowsLinux上查看端口被什么进程占用|端口占用

Windows上 查看端口占用&#xff1a; netstat -aon|findstr <端口号> 通过进程ID查询进程信息 tasklist | findstr <上一步查出来的进程号> 图例&#xff1a; Linux 上 查看端口占用&#xff1a; netstat -tuln | grep <端口号> lsof -i:<端口号&…...

函数的扩展

文章目录 函数的扩展1.函数参数的默认值1.1 基本用法-- 参数变量是默认声明的&#xff0c;所以不能用 let或const 再次声明-- 使用参数默认值时&#xff0c;函数不能有同名参数1.2 与解构赋值默认值结合使用☆☆☆ 函数参数的默认值生效以后&#xff0c;参数解构赋值依然会进行…...

Cypress安装使用

node.js 安装使用Cypress总是会看见node.js&#xff0c;那就先看看node.js是什么。JavaScript以前运行需要在浏览器中&#xff08;浏览器内置解释器&#xff09;&#xff0c;通过node.js框架内置v8引擎&#xff08;也就是可以执行js脚本所需的工具&#xff09;&#xff0c;这样…...

2026本地视频怎么去水印?5款免费去水印软件对比和实用方法指南

很多人都遇到过这个问题&#xff1a;辛辛苦苦保存下来的视频、素材库里的片段&#xff0c;上面都贴了水印&#xff0c;想要二次编辑或重新发布时&#xff0c;这些水印就成了"眼中钉"。本地视频怎么去水印&#xff1f;2026年有哪些靠谱的免费去水印方法&#xff1f;今…...

从ok-skills项目解析技能树:设计理念、技术实现与工程实践

1. 项目概述与核心价值最近在GitHub上看到一个挺有意思的项目&#xff0c;叫“ok-skills”。光看这个名字&#xff0c;可能有点摸不着头脑&#xff0c;但点进去一看&#xff0c;发现这是一个关于“技能树”或“知识图谱”的开源项目。简单来说&#xff0c;它试图用一种结构化的…...

机器人抓取技能自动化:从仿真学习到现实迁移的实践指南

1. 项目概述与核心价值最近在机器人抓取领域&#xff0c;一个名为simpliolabs/manus-open-claw-skill-hunter-and-developer的项目引起了我的注意。乍一看这个标题&#xff0c;它像是一个开源工具或框架&#xff0c;核心围绕着“机械手开放爪具”的“技能猎人”与“开发者”。这…...

终极无边框游戏窗口指南:三步实现无缝多任务体验

终极无边框游戏窗口指南&#xff1a;三步实现无缝多任务体验 【免费下载链接】Borderless-Gaming Play your favorite games in a borderless window; no more time consuming alt-tabs. 项目地址: https://gitcode.com/gh_mirrors/bo/Borderless-Gaming 你是否厌倦了在…...

Rust嵌入式开发实战:开源机械爪控制库openclaw-rs架构解析与应用

1. 项目概述&#xff1a;当Rust遇上开源机械爪最近在逛GitHub的时候&#xff0c;偶然发现了一个挺有意思的项目——neul-labs/openclaw-rs。光看名字&#xff0c;你大概能猜到它是个用Rust语言写的、跟机械爪&#xff08;Claw&#xff09;相关的开源项目。没错&#xff0c;这正…...

跨平台资源下载神器:3分钟掌握全网视频音频一键保存终极指南

跨平台资源下载神器&#xff1a;3分钟掌握全网视频音频一键保存终极指南 【免费下载链接】res-downloader 视频号、小程序、抖音、快手、小红书、直播流、m3u8、酷狗、QQ音乐等常见网络资源下载! 项目地址: https://gitcode.com/GitHub_Trending/re/res-downloader 还在…...

别再只用脚本了!用MATLAB面向对象编程重构你的科研数据处理流程(附完整Point类示例)

别再只用脚本了&#xff01;用MATLAB面向对象编程重构你的科研数据处理流程&#xff08;附完整Point类示例&#xff09; 科研数据处理中&#xff0c;你是否经常遇到这样的场景&#xff1a;同一个实验数据需要反复处理&#xff0c;每次都要复制粘贴大段脚本&#xff1b;变量命名…...

CodeWarrior IDE文件操作与ARM开发实践

1. CodeWarrior IDE文件操作深度解析在嵌入式开发领域&#xff0c;文件操作的高效管理直接影响着开发效率和代码安全性。作为ARM开发的经典工具链组件&#xff0c;CodeWarrior IDE提供了一套完整的文件管理机制&#xff0c;特别适合处理ARM架构的嵌入式项目。我使用这套工具开发…...

终极Python通达信数据读取指南:5分钟快速入门量化分析

终极Python通达信数据读取指南&#xff1a;5分钟快速入门量化分析 【免费下载链接】mootdx 通达信数据读取的一个简便使用封装 项目地址: https://gitcode.com/GitHub_Trending/mo/mootdx 在金融数据分析和量化交易领域&#xff0c;通达信数据读取一直是Python开发者面临…...

霍夫曼编码:让计算机学会“断舍离“的无损压缩原理,为什么Zip文件能完美还原,而JPEG会失真?霍夫曼用一棵二叉树解决了50年的压缩难题

霍夫曼编码&#xff1a;让计算机学会"断舍离"的无损压缩原理 副标题: 为什么Zip文件能完美还原&#xff0c;而JPEG会失真&#xff1f;霍夫曼用一棵二叉树解决了50年的压缩难题痛点&#xff1a;为什么压缩文件能完美还原&#xff1f; 你用WinRAR压缩了一个Word文档&am…...