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

2024-04-26 01:04
文章标签 方式 版本 上传 若伊

本文主要是介绍文件上传方式三(若伊版本),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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.chinasem.cn/article/936291

相关文章

Jsoncpp的安装与使用方式

《Jsoncpp的安装与使用方式》JsonCpp是一个用于解析和生成JSON数据的C++库,它支持解析JSON文件或字符串到C++对象,以及将C++对象序列化回JSON格式,安装JsonCpp可以通过... 目录安装jsoncppJsoncpp的使用Value类构造函数检测保存的数据类型提取数据对json数

Redis事务与数据持久化方式

《Redis事务与数据持久化方式》该文档主要介绍了Redis事务和持久化机制,事务通过将多个命令打包执行,而持久化则通过快照(RDB)和追加式文件(AOF)两种方式将内存数据保存到磁盘,以防止数据丢失... 目录一、Redis 事务1.1 事务本质1.2 数据库事务与redis事务1.2.1 数据库事务1.

Linux磁盘分区、格式化和挂载方式

《Linux磁盘分区、格式化和挂载方式》本文详细介绍了Linux系统中磁盘分区、格式化和挂载的基本操作步骤和命令,包括MBR和GPT分区表的区别、fdisk和gdisk命令的使用、常见的文件系统格式以... 目录一、磁盘分区表分类二、fdisk命令创建分区1、交互式的命令2、分区主分区3、创建扩展分区,然后

Linux中chmod权限设置方式

《Linux中chmod权限设置方式》本文介绍了Linux系统中文件和目录权限的设置方法,包括chmod、chown和chgrp命令的使用,以及权限模式和符号模式的详细说明,通过这些命令,用户可以灵活... 目录设置基本权限命令:chmod1、权限介绍2、chmod命令常见用法和示例3、文件权限详解4、ch

Java中的密码加密方式

《Java中的密码加密方式》文章介绍了Java中使用MD5算法对密码进行加密的方法,以及如何通过加盐和多重加密来提高密码的安全性,MD5是一种不可逆的哈希算法,适合用于存储密码,因为其输出的摘要长度固... 目录Java的密码加密方式密码加密一般的应用方式是总结Java的密码加密方式密码加密【这里采用的

Java中ArrayList的8种浅拷贝方式示例代码

《Java中ArrayList的8种浅拷贝方式示例代码》:本文主要介绍Java中ArrayList的8种浅拷贝方式的相关资料,讲解了Java中ArrayList的浅拷贝概念,并详细分享了八种实现浅... 目录引言什么是浅拷贝?ArrayList 浅拷贝的重要性方法一:使用构造函数方法二:使用 addAll(

使用Python实现大文件切片上传及断点续传的方法

《使用Python实现大文件切片上传及断点续传的方法》本文介绍了使用Python实现大文件切片上传及断点续传的方法,包括功能模块划分(获取上传文件接口状态、临时文件夹状态信息、切片上传、切片合并)、整... 目录概要整体架构流程技术细节获取上传文件状态接口获取临时文件夹状态信息接口切片上传功能文件合并功能小

Mycat搭建分库分表方式

《Mycat搭建分库分表方式》文章介绍了如何使用分库分表架构来解决单表数据量过大带来的性能和存储容量限制的问题,通过在一对主从复制节点上配置数据源,并使用分片算法将数据分配到不同的数据库表中,可以有效... 目录分库分表解决的问题分库分表架构添加数据验证结果 总结分库分表解决的问题单表数据量过大带来的性能

SpringBoot项目引入token设置方式

《SpringBoot项目引入token设置方式》本文详细介绍了JWT(JSONWebToken)的基本概念、结构、应用场景以及工作原理,通过动手实践,展示了如何在SpringBoot项目中实现JWT... 目录一. 先了解熟悉JWT(jsON Web Token)1. JSON Web Token是什么鬼

在C#中合并和解析相对路径方式

《在C#中合并和解析相对路径方式》Path类提供了几个用于操作文件路径的静态方法,其中包括Combine方法和GetFullPath方法,Combine方法将两个路径合并在一起,但不会解析包含相对元素... 目录C#合并和解析相对路径System.IO.Path类幸运的是总结C#合并和解析相对路径对于 C