JAVA 文件上传下载工具类

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.UUID;/**
* 文件操作工具类
* @date  2020/8/4 - 14:20
*/
@Slf4j
public class FileUtil extends FileUtils{/*** 读取服务器相对路径下的文件并下载* @param request 请求* @param response 响应* @param srcPath 源文件路径* @param targetName 响应文件名称* @param delSrcFile 是否删除源文件* @since 2020/8/4 14:00* @author liudongxin*/public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String srcPath, String targetName,boolean delSrcFile) {try {// 读取源文件File file = readLocalFile(uploadPath + srcPath);if(StringUtils.isNotNull(file)){//文件不存在if (!file.exists() || file.isDirectory()) {log.error("要下载的文件不存在!");throw new CustomException("对不起!您要下载的文件不存在!");}//设置响应类型并下载download(request,response,file,targetName);//删除源文件if(delSrcFile){if(!file.delete()){throw new CustomException("下载文件,删除源文件失败!");}}}else {log.error("资源不存在或路径不正确");throw new CustomException("对不起!您要下载的资源不存在!");}} catch (Exception ex) {log.error(CustomException.getExceptionDetail(ex));throw new CustomException("下载资源出错了!");}}/*** 读取本工程类路径下的文件并下载* @param request 请求* @param response 响应* @param srcPath 源文件路径* @param targetName 响应文件名称* @param delSrcFile 是否删除源文件* @since 2020/8/4 14:00*/public static void downloadResFile(HttpServletRequest request, HttpServletResponse response, String srcPath, String targetName, boolean delSrcFile) {try {// 读取源文件ClassPathResource classPathResource = readLocalResFile(srcPath);if(StringUtils.isNotNull(classPathResource)){//文件不存在if (!classPathResource.getFile().exists() || classPathResource.getFile().isDirectory()) {log.error("要下载的文件不存在!");throw new CustomException("对不起!您要下载的文件不存在!");}//设置响应类型并下载download(request,response,classPathResource.getFile(),targetName);//删除源文件if(delSrcFile){if(!classPathResource.getFile().delete()){throw new CustomException("下载文件,删除源文件失败!");}}}else {log.error("资源不存在或路径不正确");throw new CustomException("对不起!您要下载的资源不存在!");}} catch (Exception ex) {log.error(CustomException.getExceptionDetail(ex));throw new CustomException("下载资源出错了!");}}/*** @param request 请求* @param response 响应* @param file 要下载的文件* @param targetName 响应文件名称*/private static void download(HttpServletRequest request, HttpServletResponse response, File file, String targetName) {//输入流FileInputStream in = null;//输出流OutputStream out = null;try {//读取文件in = new FileInputStream(file);//设置响应类型String strContentType = getFileContentType(getExt(targetName));response.reset();//重置响应response.setContentType(strContentType);//获得输出流out = response.getOutputStream();//设置编码格式if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {targetName = URLEncoder.encode(targetName, StandardCharsets.UTF_8.displayName());} else {targetName = new String(targetName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);}//设置响应头response.setHeader("Content-Disposition", "attachment;filename="+targetName);response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "No-cache");response.setDateHeader("Expires", 0);//设置显示响应文件大小response.setContentLength(in.available());byte[] buf = new byte[1024];int len;while((len = in.read(buf)) != -1){//输出响应out.write(buf, 0, len);}}catch (Exception e){log.error(CustomException.getExceptionDetail(e));throw new CustomException("下载资源出错了!");}finally {try {if(out != null){out.flush();out.close();}if(in != null){in.close();}} catch (IOException e) {log.error(CustomException.getExceptionDetail(e));}}}/*** 读取服务器相对路径下的文件* @since 2020/8/4 14:30*/public static File readLocalFile(String resourcePath) {File file = new File(resourcePath);//文件存在if(file.exists()) {return file;}else {if(file.isDirectory()){//不存在创建文件夹if(!file.mkdirs()){throw new CustomException(resourcePath + " 文件夹不存在,主动创建失败!");}return file;}return null;}}/*** 读取本工程内类路径下的文件* @since 2020/8/4 14:30*/public static ClassPathResource readLocalResFile(String resourcePath) {ClassPathResource classPathResource = new ClassPathResource(resourcePath);//文件存在if(classPathResource.exists()) {return classPathResource;}return null;}/*** 单文件上传,指定路径 0文件为空  1成功  2异常* @since 2020/8/4 14:50*/public static int saveSingleFile(File file,String targetDirectory) {try {//判断文件夹是否存在,不存在则创建File filePath = checkAndCreateFile(targetDirectory);if (file != null) {String realName = UUID.randomUUID().toString()+ getExt(file.getName());File target = new File(filePath, realName);FileUtils.copyFile(file, target);return 1;}return 0;} catch (Exception e) {log.error(e.getMessage());}return 2;}/*** 单文件上传 0文件为空  1成功  2异常* @since 2020/8/4 14:53*/public static int saveSingleFile(File file) {try {//判断文件夹是否存在,不存在则创建File filePath = checkAndCreateFile();if (file != null) {String realName = UUID.randomUUID().toString() + getExt(file.getName());File target = new File(filePath, realName);FileUtils.copyFile(file, target);return 1;}return 0;} catch (Exception e) {log.error(e.getMessage());}return 2;}/*** 单文件上传 0文件为空  1成功  2异常* @since 2020/8/4 15:00*/public static File saveFile(File file) {try {//判断文件夹是否存在,不存在则创建File filePath = checkAndCreateFile();String realName = UUID.randomUUID().toString() + getExt(file.getName());File target = new File(filePath, realName);FileUtils.copyFile(file, target);return target;} catch (Exception e) {log.error(e.getMessage());}return null;}/*** 多文件上传,指定路径 0文件为空  1成功  2异常* @since 2020/8/4 15:05*/public static int saveFile(List<File> files,String targetDirectory) {try {//判断文件夹是否存在,不存在则创建File filePath = checkAndCreateFile(targetDirectory);if (files != null) {for (File file : files) {String realName = UUID.randomUUID().toString() + getExt(file.getName());File target = new File(filePath, realName);FileUtils.copyFile(file, target);}return 1;}return 0;} catch (Exception e) {log.error(e.getMessage());}return 2;}/*** 多文件上传  0文件为空  1成功  2异常* @since 2020/8/4 15:11*/public static int saveFile(List<File> files) {try {//判断文件夹是否存在,不存在则创建File filePath = checkAndCreateFile();if (files != null) {for (File file : files) {String realName = UUID.randomUUID().toString() + getExt(file.getName());File target = new File(filePath.getPath(), realName);FileUtils.copyFile(file, target);}return 1;}return 0;} catch (Exception e) {log.error(e.getMessage());}return 2;}/*** MultipartFile 转 File并存储到指定路径* @param multipartFile 需要转换的文件* @param targetPath 转换过后的文件存放的路径* @since 2020/9/4 15:14*/public static File multipartFileToFile(MultipartFile multipartFile,String targetPath) throws Exception {File newFile = new File(targetPath);//开始转换FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), newFile);return newFile;}/*** MultipartFile 转 File并存储到默认路径* @author liudongxin* @since 2020/8/4 15:54*/public static File multipartFileToFile(MultipartFile file) throws Exception {//判断文件夹是否存在,不存在则创建File filePath = checkAndCreateFile();//转换后的文件File toFile = null;//文件不为空,进行转换if(null != file  && file.getSize() > 0){InputStream ins =  file.getInputStream();toFile = new File(filePath, Objects.requireNonNull(file.getOriginalFilename()));toFile = inputStreamToFile(ins, toFile);ins.close();}return toFile;}/*** MultipartFile 转 File,具体转换方法* @since 2020/8/4 15:55*/private static File inputStreamToFile(InputStream ins, File file) {OutputStream os = null;try {os = new FileOutputStream(file);int bytesRead;byte[] buffer = new byte[4096];while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {os.write(buffer, 0, bytesRead);}return file;} catch (Exception e) {log.error(e.getMessage());}finally {try {if(os != null){os.close();}if(ins != null){ins.close();}} catch (IOException e) {log.error(e.getMessage());}}return null;}/*** 判断文件夹是否存在,不存在则创建*/private static File checkAndCreateFile(String targetDirectory) {File filePath = new File(targetDirectory);//文件夹不存在if(!filePath.exists()){//创建if(!filePath.mkdir()){log.error("创建文件夹: "+ filePath.getName() +" 失败");throw new CustomException("创建文件夹: "+ filePath.getName() +" 失败");}}return filePath;}/*** 判断文件夹是否存在,不存在则创建*/private static File checkAndCreateFile() {File filePath = new File(uploadPath);//文件夹不存在if(!filePath.exists()){//创建if(!filePath.mkdir()){log.error("创建文件夹: "+ filePath.getName() +" 失败");throw new CustomException("创建文件夹: "+ filePath.getName() +" 失败");}}return filePath;}/*** 截取文件名除去扩展名* @date 2020/8/4 16:11*/public static String getPrefix(String fileName) {return fileName.substring(0,fileName.lastIndexOf(".")).toLowerCase();}/*** 截取文件扩展名* @since 2020/8/4 16:11* @author liudongxin*/public static String getExt(String fileName) {return fileName.substring(fileName.lastIndexOf(".")).toLowerCase();}/*** 设根据文件类型置响应类型* @since 2020/8/4 16:11*/private static String getFileContentType(String strFileExt) {String strContentType;if ((strFileExt == null) || ((strFileExt = strFileExt.trim().toLowerCase()).length() == 0)) {strContentType = "text/plain";return  strContentType;}switch (strFileExt){case ".sql":strContentType = "text/txt";break;case ".html":case ".htm":strContentType = "text/html";break;case ".xml":case ".xsl":strContentType = "text/xml";break;case ".zip":strContentType = "application/zip";break;case ".exe":strContentType = "application/exec";break;case ".gif":strContentType = "image/gif";break;case ".jpe":case ".jpeg":case ".jpg":strContentType = "image/jpeg";break;case ".pdf":strContentType = "application/pdf";break;case ".doc":case ".rtf":strContentType = "application/msword";break;case ".ppt":strContentType = "application/vnd.ms-powerpoint";break;case ".xls":case ".xlsx":strContentType = "application/vnd.ms-excel";break;case ".ceb":strContentType = "application/x-ceb";break;case ".ftl":strContentType = "application/force-download";break;default:strContentType = "application/octet-stream";break;}return strContentType;}}

JAVA 文件上传下载工具类相关推荐

  1. java文件上传下载工具类FileUtils

    上传: package com.yonyougov.dmp.amserver.utils;import com.alibaba.fastjson.JSON; import org.slf4j.Logg ...

  2. 华为云OBS文件上传下载工具类

    Java-华为云OBS文件上传下载工具类 文章目录 Java-华为云OBS文件上传下载工具类 1.华为云obs文件上传下载 2.文件流转MultipartFile 3.File转换为Multipart ...

  3. springboot+minio文件上传下载工具类

    引入依赖 <dependency><groupId>io.minio</groupId><artifactId>minio</artifactId ...

  4. 阿里云OSS文件上传下载工具类

    引入依赖 <dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss ...

  5. springboot上传下载文件(4)--上传下载工具类(已封装)

    因为在做毕设,发现之前的搭建ftp文件服务器,通过ftp协议无法操作虚拟机临时文件,又因为ftp文件服务器搭建的比较麻烦:而 hadoop的HDFS虽然可以实现,但我这里用不到那么复杂的:所以我封装了 ...

  6. 2021-10-14 ContextType(MIME) 与 Java文件上传/下载

    ContextType(MIME) 与 Java文件上传/下载 ContextType(MIME) Text Image Audio Video Application Multipart 和 Mes ...

  7. Java文件上传下载

    文件上传下载 Java文件上传和下载对于刚接触Java没多久的老铁们来说可能是一个技术难点.如果看过我前两篇文章的老铁肯定就知道,这次肯定又是一个工具类,废话少说我们直接附上代码. package c ...

  8. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:宇的季节 cnblogs.com/chenkeyu/p/80 ...

  9. java 文件 上传 下载

    QuFileUtil web_uploader.html <!DOCTYPE html> <html lang="en"> <head> < ...

最新文章

  1. 关于Spring Cloud 框架热部署的方法
  2. 经典角点检测算法实现
  3. Luogu P4709 信息传递 (群论、生成函数、多项式指数函数)
  4. Python连接MySQL及一系列相关操作
  5. 2020 OPPO开发者大会:融合共创 打造多终端、跨场景的智能化生活
  6. 心理压力如何测试软件,心理压力测试 缓解压力有什么办法
  7. drawnow aviread
  8. PowerDesigner16使用方法
  9. 基本农田卫星地图查询_水经注万能地图下载器软件主界面功能说明
  10. android 模拟点击屏幕,按键精灵后台简明教程(后台找色,后台鼠标点击等)
  11. abd串口工具使用教程_adb调试工具包(adb调试程序)
  12. 数据分析的坑,都在统计学里埋过
  13. 用python做生信_1 python生信入门
  14. 安装windows系统到移动硬盘
  15. updating mysql.pid_启动mysql ERROR! The server quit without updating PID file
  16. PHP 开源 ERP 系统 Discover
  17. 外贸找客户软件:Email Extractor Pro
  18. 2022寒假---冲冲冲~
  19. 网易16年研发实习生笔试题 - 寻找第K大
  20. 怎样设计才能让文字排版更好看(一)

热门文章

  1. QTP - Object Identification
  2. pythonxy官网下载_GitHub - wptyut/codeparkshare: Python初学者(零基础学习Python、Python入门)书籍、视频、资料、社区推荐...
  3. 使用电脑摄像头识别二维码
  4. 微信获取openID以及token
  5. 服务器登录密码 被修改密码,服务器登录密码被人改
  6. 如何显示密件抄送人员地址_发送电子邮件时,抄送和密件抄送有什么区别?
  7. 基于springboot的在线考试系统的设计与实现 毕业设计毕设参考
  8. 微信支付V3 生成平台证书
  9. 如何根据英文地址查到国外的经纬度
  10. sql 查询_嵌套查询