文件上传方式三(若伊版本)

1.准备配置类

package com.ruoyi.screen.core;

public class MimeTypeUtils
{
    public static final String IMAGE_PNG = "image/png";

    public static final String IMAGE_JPG = "image/jpg";

    public static final String IMAGE_JPEG = "image/jpeg";

    public static final String IMAGE_BMP = "image/bmp";

    public static final String IMAGE_GIF = "image/gif";
    
    public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };

    public static final String[] FLASH_EXTENSION = { "swf", "flv" };

    public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
            "asf", "rm", "rmvb" };

    public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" };

    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            // 图片
            "bmp", "gif", "jpg", "jpeg", "png",
            // word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            // 压缩文件
            "rar", "zip", "gz", "bz2",
            // 视频格式
            "mp4", "avi", "rmvb",
            // pdf
            "pdf" };

    public static String getExtension(String prefix)
    {
        switch (prefix)
        {
            case IMAGE_PNG:
                return "png";
            case IMAGE_JPG:
                return "jpg";
            case IMAGE_JPEG:
                return "jpeg";
            case IMAGE_BMP:
                return "bmp";
            case IMAGE_GIF:
                return "gif";
            default:
                return "";
        }
    }
}

2工具类配置

1.获取上传文件后的url配置

@Component
public class ServerConfig
{
    /**
     * 获取完整的请求路径,包括:域名,端口,上下文访问路径
     * 
     * @return 服务地址
     */
    public String getUrl()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
}

2.service配置

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ruoyi.screen.core;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Objects;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadUtils {
    public static final long DEFAULT_MAX_SIZE = 52428800L;
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;
    private static String defaultBaseDir = RuoYiConfig.getProfile();
    private static final String SECRET_KEY = "MySecretKey1234";

    public FileUploadUtils() {
    }

    public static void setDefaultBaseDir(String defaultBaseDir) {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir() {
        return defaultBaseDir;
    }

    private static SecretKey generateSecretKey() throws Exception {
        KeySpec keySpec = new PBEKeySpec("MySecretKey1234".toCharArray(), "MySecretKey1234".getBytes(), 128, 256);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        byte[] secretKeyBytes = secretKeyFactory.generateSecret(keySpec).getEncoded();
        return new SecretKeySpec(secretKeyBytes, "AES");
    }

    public static final String upload(MultipartFile file) throws IOException {
        try {
            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception var2) {
            throw new IOException(var2.getMessage(), var2);
        }
    }

    public static final String upload(String baseDir, MultipartFile file) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception var3) {
            throw new IOException(var3.getMessage(), var3);
        }
    }

    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws Exception {
        int fileNamelength = ((String)Objects.requireNonNull(file.getOriginalFilename())).length();
        if (fileNamelength > 100) {
            throw new FileNameLengthLimitExceededException(100);
        } else {
            assertAllowed(file, allowedExtension);
            String fileName = extractFilename(file);
            //String fileName = "shebei.xlsx";
            String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
            file.transferTo(Paths.get(absPath));
            return getPathFileName(baseDir, fileName);
        }
    }

    public static final String extractFilename(MultipartFile file) throws Exception {
        String uniqueIdentifier = generateUniqueIdentifier();
        return StringUtils.format("{}/{}_{}", new Object[]{DateUtils.datePath(), encodeBase64Url(file.getOriginalFilename()), uniqueIdentifier});
    }

    private static String generateUniqueIdentifier() {
        return String.valueOf(System.currentTimeMillis());
    }

    public static String encodeBase64Url(String input) {
        byte[] encodedBytes = Base64.getUrlEncoder().encode(input.getBytes(StandardCharsets.UTF_8));
        return new String(encodedBytes, StandardCharsets.UTF_8);
    }

    public static String decodeBase64Url(String input) {
        byte[] decodedBytes = Base64.getUrlDecoder().decode(input.getBytes(StandardCharsets.UTF_8));
        return new String(decodedBytes, StandardCharsets.UTF_8);
    }

    public static String encryptFileName(String fileName) throws Exception {
        SecretKey secretKey = generateSecretKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(1, secretKey);
        byte[] encryptedBytes = cipher.doFinal(fileName.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decryptFileName(String encryptedFileName) throws Exception {
        SecretKey secretKey = generateSecretKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(2, secretKey);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedFileName);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }

    public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.exists() && !desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }

        return desc;
    }

    public static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return "/profile/" + currentDir + "/" + fileName;
    }

    public static final void assertAllowed(MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, InvalidExtensionException {
        long size = file.getSize();
        if (size > 52428800L) {
            throw new FileSizeLimitExceededException(50L);
        } else {
            String fileName = file.getOriginalFilename();
            String extension = getExtension(file);
            if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
                if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                    throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, fileName);
                } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                    throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, fileName);
                } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                    throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName);
                } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
                    throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension, fileName);
                } else {
                    throw new InvalidExtensionException(allowedExtension, extension, fileName);
                }
            }
        }
    }

    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        String[] var2 = allowedExtension;
        int var3 = allowedExtension.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String str = var2[var4];
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }

        return false;
    }

    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension((String)Objects.requireNonNull(file.getContentType()));
        }

        return extension;
    }
}

3.调用上传

 public String insertKnowledgeDocumentsFiles(List<MultipartFile> file) {
        try
        {   // 上传文件路径
            String filePath =profile+"/xlsx";
            LoggerHelper.info("文件上传路径:"+profile);
             // 上传并返回新文件名称
            if (file != null && !file.isEmpty()) {
                for (MultipartFile file1 : file) {
               String fileName = FileUploadUtils.upload(filePath, file1);
                String url = serverConfig.getUrl() + fileName;
                String newFileName = FileUtils.getName(fileName) ;
                String originalFilename = file1.getOriginalFilename() ;
                System.out.println(fileName);
                System.out.println(url);
                System.out.println(newFileName);
                System.out.println(originalFilename);
                }
            }
            return "ok";

        }
        catch (Exception e)
        {

        LoggerHelper.error(e.getMessage());
            return "FilesUploadError";
        }
    }

4.文件下载使用

 @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

 

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Stable Diffusion中的embedding

Stable Diffusion中的embedding 嵌入&#xff0c;也称为文本反转&#xff0c;是在 Stable Diffusion 中控制图像样式的另一种方法。在这篇文章中&#xff0c;我们将学习什么是嵌入&#xff0c;在哪里可以找到它们&#xff0c;以及如何使用它们。 什么是嵌入embedding&#xf…

Axure设计美观友好的后台框架页

使用Axure设计后台框架页 优点介绍&#xff1a; **1、使用中继器灵活配置菜单项&#xff1b; 2、二级菜单面板跟随一级菜单位置显示&#xff1b; 3、菜单链接打开后&#xff0c;联动添加tab标签&#xff1b; 4、标签页与iframe内容联动&#xff0c;可关闭&#xff1b; 5、左侧…

SpringBoot集成Sharding-JDBC实现主从同步

SpringBoot集成Sharding-JDBC实现主从同步 1.mysql主从配置2.application.properties文件配置3.测试3.1 查询数据3.2 添加数据 1.mysql主从配置 详细内容请参考上一篇文章&#xff1a;MySQL8.0以上实现主从同步配置 2.application.properties文件配置 # ShardingSphere conf…

通过本机端口映射VMware中虚拟机应用(例如同一局域网别人想远程连接你虚拟机中的数据库)

需要 虚拟机中安装一下达梦数据库&#xff0c;并且以后大家都连接你虚拟机中达梦数据库进行开发。。。。。。在不改动自己虚拟机配置&#xff0c;以及本地网卡任何配置的情况下如何解决&#xff1f;本虚拟机网络一直使用的NAT模式。 解决 找到NAT设置添加端口转发即可解决。…

Git for Windows 下载与安装

当前环境&#xff1a;Windows 8.1 x64 1 打开网站 https://git-scm.com/ &#xff0c;点击 Downloads 。 2 点击 Windows 。 3 选择合适的版本&#xff0c;这里选择了 32-bit Git for Windows Portable。 4 解压下载后的 PortableGit-2.44.0-32-bit.7z.exe &#xff0c;并将 P…

运营商三要素核验接口-手机实名验证API

运营商三要素核验接口是一种API&#xff08;Application Programming Interface&#xff0c;应用程序编程接口&#xff09;&#xff0c;主要用于通过互联网技术对接通信运营商的实名制数据库&#xff0c;以验证用户提供的手机号码、身份证号码、姓名这三项关键信息&#xff08;…

乐鑫的ESP32-S3芯片的LE能实现beacon功能吗?

最近帮一个客户做ESP32定位器方案&#xff0c;客户提出这个疑问&#xff0c;乐鑫的ESP32-S3芯片的LE能实现beacon功能吗&#xff1f;针对这个问题&#xff0c;启明云端工程师小启给出这样的回复。 回答是可以的&#xff0c;大家可以看idf的例程。 ESP-IDF iBeacon demo From …

19 使用MapReduce编程统计超市1月商品被购买的次数

首先将1月份的订单数据上传到HDFS上&#xff0c;订单数据格式 ID Goods两个数据字段构成 将订单数据保存在order.txt中&#xff0c;&#xff08;上传前记得启动集群&#xff09;。 打开Idea创建项目 修改pom.xml&#xff0c;添加依赖 <dependencies><dependency>…

惠海 H5112B 洗墙灯24V36V48V60V72V100V1.2ALED降压恒流芯片IC PWM无频闪调光

洗墙灯24V36V48V60V72V100V1.2A LED降压恒流芯片PWM无频闪调光是一种特殊的电子元件&#xff0c;专为洗墙灯等LED照明设备设计。以下是关于这种芯片的主要特点和功能&#xff1a; 降压恒流功能&#xff1a;该芯片能够将较高的输入电压&#xff08;如24V、36V、48V等&#xff0…

【机器学习】集成学习---投票法(Voting)

一、引言 集成学习&#xff08;Ensemble Learning&#xff09;是机器学习领域中的一种重要策略&#xff0c;它通过结合多个模型的预测结果来提高整体性能。在单个模型容易过拟合或欠拟合的情况下&#xff0c;集成学习能够通过综合多个模型的优点来减少这种风险&#xff0c;从而…

三 SpringMVC返回数据以及RESTFul设计标准

SpringMVC返回数据 一 控制页面跳转 1.1 快速使用 开发模式回顾在 Web 开发中&#xff0c;有两种主要的开发模式&#xff1a;前后端分离和混合开发。前后端分离模式&#xff1a;[重点]指将前端的界面和后端的业务逻辑通过接口分离开发的一种方式。开发人员使用不同的技术栈和…

Oracle 21 C 安装详细操作手册,并配置客户端连接

Oracle 21 C 安装详细操作手册 Win 11 Oracle 21C 下载&#xff1a; Database Software Downloads | Oracle 中国 云盘共享 链接&#xff1a;https://pan.baidu.com/s/12XCilnFYyLFnSVoU_ShaSA 提取码&#xff1a;nfwc Oracle 21C 配置与登陆&#xff1a; 开始菜单 NetMa…

第三节课,后端登录【1】

一、总任务 二、登录接口 get 请求&#xff0c;有缺陷&#xff0c;长度有限制 三、登录逻辑 四、代码书写位置 4.1 编写业务逻辑的位置 五、写代码 5.1 代码1 5.1.1 细节 按 CtrlAltShiftL ,快速格式化 5.1. 2 自动生成接口参数 先/** 再回车 效果图 5.2 按 alt enter …

SpringBoot (批量)生成二维码工具类多种方法示例

一、引入依赖 <dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.4.1</version> </dependency><dependency><groupId>com.google.zxing</groupId><artifactId…

Python之PCV库安装教程以及解说

PCV库是一个比较古老的python库 在网上参考了很多教程 于是现在想要总结一下,并且分享整理了一下资源 很多人是通过pycharm内部直接下载PCV 但是导入时还要报错 因为PCV版本不对 pycharm自动下载的版本过于旧 是0.0.2 而我们需要的是1.0.0版本 否则下面PCV部分会报错无法导入…

Android—统一依赖版本管理

依赖版本管理有多种方式 config.gradle 用于Groovy DSL&#xff0c;新建一个 config.gradle 文件&#xff0c;然后将项目中所有依赖写在里面&#xff0c;更新只需修改 config.gradle文件内容&#xff0c;作用于所有module buildSrc 可用于Kotlin DSL或Groovy DSL&#xff0c;…

阿里服务器centos7宝塔部署docker-compose项目

这里写目录标题 整体项目所使用的服务如下阿里云服务器操作安装宝塔面板小程序docker部署如果报错容器数量显示0 最近搞了个AI角色游戏的小程序&#xff0c;玩一玩练练手&#xff0c;因为项目需要复制部署&#xff0c;就研究下了docker&#xff0c;然后客户很多都是宝塔&#x…

【CMU15-445 Part-19】Multi-Version Concurrency Control

Part19-Multi-Version Concurrency Control 其实说到底 MVCC不仅是一种并发控制协议&#xff0c;更是一个系统构建&#xff08;数据组织的方法&#xff09;。 简介 writer 不会 block readers&#xff0c;reader 也不会 block writers。只读事务可以读到一个consistent的sna…

Clion连接MySQL数据库:实现C/C++语言与MySQL交互

确保你的电脑里已经有了MySQL。 1、找到MySQL的目录 2、进入lib目录 3、复制libmysql.dll和libmysql.lib文件 4、将这俩文件粘贴到你的clion项目的cmake-build-debug目录下 如果不是在这个目录下&#xff0c;运行时会出以下错误报错&#xff1a; 进程已结束&#xff0c;退…

【go零基础】go-zero从零基础学习到实战教程 - 2项目初始化

到项目初始化过程了&#xff0c;这边的项目设计完全按照作者自己的喜好来进行定义和设置的&#xff0c;所以各位完全可以按照自己的偏好自喜设置哈。 首先是创建一个工作文件夹哈。 别问为啥不直接quickstart&#xff0c;因为quickstart生成的api名字是greet&#xff0c;改起来…
最新文章