当前位置: 首页 > 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();}}
}
http://www.lryc.cn/news/197530.html

相关文章:

  • 内燃机可变气门驱动研究进展
  • NEFU离散数学实验2-容斥原理
  • 解决Windows内存溢出/占满死机问题-PoolMon工具
  • 【ROS】ros-noetic和anaconda联合使用【教程】
  • 自动化RPA开发 --获取所有窗口信息和进程信息
  • 【Qt之布局】QVBoxLayout、QHBoxLayout、QGridLayout、QFormLayout介绍及使用
  • 【计算机毕业设计】python在线课程培训学习考试系统637r7-PyCharm项目
  • vue3后台管理系统之登录界面和业务的实现
  • GEE19:基于Landsat8的常见的植被指数逐年获取
  • Python【多分支实际应用的练习】
  • LeetCode 343. 整数拆分(动态规划)
  • C++对象模型(12)-- 构造函数语义学:构造函数
  • [23] T^3Bench: Benchmarking Current Progress in Text-to-3D Generation
  • linux系统如何定时关机
  • 构建高性能物联网数据平台:EMQX和CnosDB的完整教程
  • 【vim 学习系列文章 11 -- vim filetype | execute | runtimepath 详细介绍】
  • [备忘]WindowsLinux上查看端口被什么进程占用|端口占用
  • 函数的扩展
  • Cypress安装使用
  • 怎么把图片改成jpg格式?
  • [一带一路金砖 2023 CTF]Crypto
  • FPGA【Verilog语法】
  • Flume 整合 Kafka
  • VUE:侧边弹出栏组件,组件中有树状图,搜索框可筛选树状图节点,可收缩
  • 如何使用pytorch定义一个多层感知神经网络模型——拓展到所有模型知识
  • 为什么引入SVG文件,给它定义属性不生效原理分析
  • Integer包装类常用方法和属性
  • 基于Spring boot轻松实现一个多数据源框架
  • vue前端实现打印功能并约束纸张大小---调用浏览器打印功能打印页面部分元素并固定纸张大小
  • 音乐播放器蜂鸣器ROM存储歌曲verilog,代码/视频