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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/109773.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++11——包装器与lambda表达式

目录 一.背景 二.lambda 1.见一见lambda 2.lambda表达式语法 3.lambda捕捉列表说明 三.函数对象与lambda表达式 四.包装器 1.function包装器 2.包装类的成员函数 五.bind 1.调整参数位置 2.减少函数参数 一.背景 在C98中&#xff0c;如果想要对一个数据集合中的元素…

成都瀚网科技:如何有效运营抖店来客呢?

随着电子商务的快速发展和移动互联网的普及&#xff0c;越来越多的企业开始将目光转向线上销售渠道。其中&#xff0c;抖音成为备受关注的平台。作为中国最大的短视频社交平台之一&#xff0c;抖音每天吸引数亿用户&#xff0c;这也为企业提供了巨大的商机。那么&#xff0c;如…

Integer包装类常用方法和属性

包装类 什么是包装类Integer包装类常用方法和属性 什么是包装类 Java 包装类是指为了方便处理基本数据类型而提供的对应的引用类型。Java 提供了八个基本数据类型&#xff08;boolean、byte、short、int、long、float、double、char&#xff09;&#xff0c;每个基本数据类型对…

F5.5G落进现实:目标网带来的光之路

数字化与智能化的世界将走向何方&#xff1f;这个问题有着非常复杂的答案&#xff0c;但其中有一个答案已经十分清晰。那就是智能化的下一步&#xff0c;必将走向泛在万兆的世界。 网络是算力联接的底座&#xff0c;是智能演化的基础。纵观每一代数字化升级&#xff0c;都可以发…

代码随想录Day22 LeetCode T39 组合总和 T40 组合总和II T131 分割回文串

LeetCode T39 组合总和 题目链接:39. 组合总和 - 力扣&#xff08;LeetCode&#xff09; 树形图 题目思路: 这我们会发现和昨天的题目很像,只是这里的元素并不是只能选取一次了,我们可以根据代码画出树形图来解决问题,下面我们开始递归三部曲 首先我们先定义出result和path数…

亲,手撸图文博文太累了?试试这个神器!

这一篇博客有关如何使用[InternLM-XComposer]来写图文并茂的博文。InternLM-XComposer是一个基于人工智能的创作工具&#xff0c;它可以根据你的输入生成不同类型的内容&#xff0c;例如文章、诗歌、歌词、代码等。你可以使用它来创作有趣和有创意的博客&#xff0c;同时也可以…

C# OpenCvSharp 利用Lab空间把春天的场景改为秋天

效果 项目 代码 using OpenCvSharp; using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms;namespace OpenCvSharp_Demo {public partial class Form1 : Form{public Form1(){InitializeComponent();}st…

免费:实时 AI 编程助手 Amazon CodeWhisperer

点 &#xff0c;一起程序员弯道超车之路 现已正式推出实时 AI 编程助手 Amazon CodeWhisperer&#xff0c;包括 CodeWhisperer 个人套餐&#xff0c;所有开发人员均可免费使用。最初于去年推出的预览版 CodeWhisperer 让开发人员能够保持专注、高效&#xff0c;帮助他们快速、安…

Java将Word转换成PDF-aspose

Java将Word转换成PDF 本文将演示用aspose-word.jar包来实现将Word转换成PDF&#xff0c;且可以保留图表和图片。 文章目录 Java将Word转换成PDF前言一、aspose是什么&#xff1f;二、使用步骤1.下载jar包2.引入库3.word 转pdf 补充1.根据模板生成word&#xff08;1&#xff09…

如何管理前端状态?

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…

计算机网络中的CSMA/CD算法的操作流程(《自顶向下》里的提炼总结)

具有碰撞检测的载波侦听多路访问&#xff08;CSMA/CD算法&#xff09; 以下内容总结&#xff0c;对应《计算机网络自顶向下第七版》第六章链路层和局域网P299 操作流程&#xff1a; NIC&#xff08;适配器&#xff0c;即网络接口&#xff09;从网络层接收数据报&#xff0c;…

OneDrive打不开了,怎么办?使用管理员身份也无效,分享解决办法如下

文章目录 1、问题描述2、解决办法2.1 修改注册表信息2.2 修改本地组策略 1、问题描述 电脑自带的 OneDrive 突然打不开了&#xff0c;双击也没有任何反应&#xff0c;以管理员身份打开也不行。去看了好多资料才解决这个问题&#xff0c;现分享如下&#xff1b; 2、解决办法 …

用友GRP-U8 SQL注入漏洞复现

0x01 产品简介 用友GRP-U8R10行政事业财务管理软件是用友公司专注于国家电子政务事业&#xff0c;基于云计算技术所推出的新一代产品&#xff0c;是我国行政事业财务领域最专业的政府财务管理软件。 0x02 漏洞概述 用友GRP-U8的bx_historyDataCheck jsp、slbmbygr.jsp等接口存…

视频批量加水印:保护版权,提升效率

在当今的自媒体时代&#xff0c;视频制作已经成为许多人的一项必备技能。然而&#xff0c;在视频制作过程中&#xff0c;如何为自己的视频添加独特的水印以保护知识产权&#xff0c;常常让许多制作者感到困扰。本文将为你揭示如何通过固乔剪辑助手软件&#xff0c;简单几步批量…

性能测试:测试常见的指标(超详细~)

前言 今天想和大家来聊聊性能测试常见的指标&#xff0c;我在这里也不喜欢说废话我们直接开始吧。 同时&#xff0c;我也为大家准备了一份软件测试视频教程&#xff08;含面试、接口、自动化、性能测试等&#xff09;&#xff0c;就在下方&#xff0c;需要的可以直接去观看&am…

JavaScript常用函数

JS字符串方法大全 JS-2490. 回环句 const list str.split( ); JS-2506. 统计相似字符串对的数目 words words.map(item > [...new Set(item)].sort().join())

电子器件系列49:CD4050B缓冲器

同相和反向缓冲器 还搞不懂缓冲电路&#xff1f;看这一文&#xff0c;工作原理作用电路设计使用方法 - 知乎 (zhihu.com) 缓冲器_百度百科 (baidu.com) 1、缓冲器的定义 缓冲器是数字元件的其中一种&#xff0c;它对输入值不执行任何运算&#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 这个配…

Python进阶(更新中)

typing Python的typing模块是Python 3.5版本引入的一个标准库&#xff0c;它提供了一种在Python代码中显式声明类型的方式&#xff0c;可以帮助开发人员更好地理解和使用Python的类型系统。 使用typing模块&#xff0c;您可以在函数、类、变量等地方添加类型注解&#xff0c;以…

VR智能家居虚拟连接仿真培训系统重塑传统家居行业

家居行业基于对场景的打造及设计&#xff0c;拥有广阔前景&#xff0c;是众多行业里面成为最有可能进行元宇宙落地的应用场景之一。 家居行业十分注重场景的打造及设计&#xff0c;而元宇宙恰恰能通过将人工智能、虚拟现实、大数据、物联网等技术融合提升&#xff0c;带来身临其…