当前位置: 首页> 游戏> 手游 > 中国跨境电商出口平台_邢台有限公司_国外域名购买_大连网站建设费用

中国跨境电商出口平台_邢台有限公司_国外域名购买_大连网站建设费用

时间:2025/7/14 23:04:32来源:https://blog.csdn.net/qq_47910339/article/details/143592896 浏览次数:0次
中国跨境电商出口平台_邢台有限公司_国外域名购买_大连网站建设费用
依赖
        <dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.5.3</version></dependency>
配置项
minio:url: http://localhost:9000accessKey: exampleAccessKeysecretKey: exampleSecretKeybucket: exampleBucketaccessUrl: http://localhost:9000/exampleBucket
配置属性绑定
@Data
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {private String url;private String accessKey;private String secretKey;private String bucket;private String accessUrl;
}
工具类:
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;/*** @Author: Cookie* @Description: Minio工具类*/
@Slf4j
public class MinioUtils {private static MinioClient minioClient;private static String endpoint;private static String accessKey;private static String secretKey;private static final String SEPARATOR = "/";private MinioUtils() {}public MinioUtils(String endpoint, String accessKey, String secretKey) {MinioUtils.endpoint = endpoint;MinioUtils.accessKey = accessKey;MinioUtils.secretKey = secretKey;createMinioClient();}/*** 创建minioClient*/public void createMinioClient() {try {if (null == minioClient) {minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();System.err.println("创建Minio通道成功!");}} catch (Exception e) {System.err.println("创建Minio通道失败!");}}/*** 获取上传文件的基础路径** @return url*/public static String getBasisUrl(String bucketName) {return endpoint + SEPARATOR + bucketName + SEPARATOR;}/*** 验证bucketName是否存在** @return boolean true:存在*/public static boolean bucketExists(String bucketName)throws Exception {return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());}/*** 创建bucket** @param bucketName bucket名称*/public static void createBucket(String bucketName)throws Exception {if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());}}/*** 获取全部bucket*/public static List<Bucket> getAllBuckets() throws Exception {return minioClient.listBuckets();}/*** 根据bucketName获取信息** @param bucketName bucket名称*/public static Optional<Bucket> getBucket(String bucketName) throws Exception {return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();}/*** 根据bucketName删除信息** @param bucketName bucket名称*/public static void removeBucket(String bucketName) throws Exception {minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());}/*** 判断文件是否存在** @param bucketName 存储桶* @param objectName 对象* @return true:存在*/public static boolean doesObjectExist(String bucketName, String objectName) {boolean exist = true;try {minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());} catch (Exception e) {exist = false;}return exist;}/*** 判断文件夹是否存在** @param bucketName 存储桶* @param objectName 文件夹名称(去掉/)* @return true:存在*/public static boolean doesFolderExist(String bucketName, String objectName) {boolean exist = false;try {Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());for (Result<Item> result : results) {Item item = result.get();if (item.isDir() && objectName.equals(item.objectName())) {exist = true;}}} catch (Exception e) {exist = false;}return exist;}/*** 根据文件前置查询文件** @param bucketName bucket名称* @param prefix     前缀* @param recursive  是否递归查询* @return MinioItem 列表*/public static List<Item> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) throws Exception {List<Item> list = new ArrayList<>();Iterable<Result<Item>> objectsIterator = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());if (objectsIterator != null) {for (Result<Item> o : objectsIterator) {Item item = o.get();list.add(item);}}return list;}/*** 通过MultipartFile,上传文件** @param bucketName  存储桶* @param file        文件* @param objectName  对象名* @param contentType 文件类型*/public static ObjectWriteResponse putObject(String bucketName, MultipartFile file, String objectName, String contentType) throws Exception {InputStream inputStream = file.getInputStream();return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType).stream(inputStream, inputStream.available(), -1).build());}/*** 通过MultipartFile,上传文件** @param bucketName 存储桶* @param file       文件* @param objectName 对象名*/public static ObjectWriteResponse putObject(String bucketName, MultipartFile file, String objectName) throws Exception {InputStream inputStream = file.getInputStream();return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(inputStream, inputStream.available(), -1).build());}/*** 上传本地文件** @param bucketName 存储桶* @param objectName 对象名称* @param filePath   文件路径(网络)*/public static ObjectWriteResponse putObject(String bucketName, String objectName, String filePath)throws Exception {URLConnection urlConnection = new URL(filePath).openConnection();return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(urlConnection.getContentType()).stream(urlConnection.getInputStream(), urlConnection.getContentLength(), -1).build());}/*** 连接参数** @param bucketName  存储桶* @param fileAbsName 文件绝对路径* @param connection  链接对象* @return* @throws Exception*/public static ObjectWriteResponse putObject(String bucketName, String fileAbsName, URLConnection connection) throws Exception {InputStream inputStream = connection.getInputStream();return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileAbsName).contentType(connection.getContentType()).stream(inputStream, inputStream.available(), -1).build());}/*** 通过流上传文件** @param bucketName  存储桶* @param objectName  文件对象* @param inputStream 文件流*/public static ObjectWriteResponse putObject(String bucketName, String objectName,InputStream inputStream)throws Exception {return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(inputStream, inputStream.available(), -1).build());}/*** 创建文件夹或目录** @param bucketName 存储桶* @param objectName 目录路径*/public static ObjectWriteResponse putDirObject(String bucketName, String objectName)throws Exception {return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(new ByteArrayInputStream(new byte[]{}), 0, -1).build());}/*** 拷贝文件** @param bucketName    bucket名称* @param objectName    文件名称* @param srcBucketName 目标bucket名称* @param srcObjectName 目标文件名称*/public static ObjectWriteResponse copyObject(String bucketName, String objectName,String srcBucketName, String srcObjectName)throws Exception {return minioClient.copyObject(CopyObjectArgs.builder().source(CopySource.builder().bucket(bucketName).object(objectName).build()).bucket(srcBucketName).object(srcObjectName).build());}/*** 文件下载** @param bucketName 桶名称* @param request    请求* @param response   请求响应*/public static void downloadFile(String bucketName, String originalName,HttpServletRequest request,HttpServletResponse response) {try {InputStream file = getObject(bucketName, originalName);//文件名乱码处理String useragent = request.getHeader("USER-AGENT").toLowerCase();if (useragent.contains("msie") || useragent.contains("like gecko") || useragent.contains("trident")) {originalName = URLEncoder.encode(originalName, StandardCharsets.UTF_8.displayName());} else {originalName = new String(originalName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);}response.setCharacterEncoding("UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + originalName);ServletOutputStream servletOutputStream = response.getOutputStream();int len;byte[] buffer = new byte[1024];while ((len = file.read(buffer)) > 0) {servletOutputStream.write(buffer, 0, len);}servletOutputStream.flush();file.close();servletOutputStream.close();} catch (Exception e) {System.err.println(String.format("下载文件:%s异常", originalName));}}/*** 获取文件流** @param bucketName bucket名称* @param objectName 文件名称* @return 二进制流*/public static InputStream getObject(String bucketName, String objectName) throws Exception {return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());}/*** 断点下载** @param bucketName bucket名称* @param objectName 文件名称* @param offset     起始字节的位置* @param length     要读取的长度* @return 流*/public InputStream getObject(String bucketName, String objectName, long offset, long length)throws Exception {return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).offset(offset).length(length).build());}/*** 获取路径下文件列表** @param bucketName bucket名称* @param prefix     文件名称* @param recursive  是否递归查找,如果是false,就模拟文件夹结构查找* @return 二进制流*/public static Iterable<Result<Item>> listObjects(String bucketName, String prefix, boolean recursive) {return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());}/*** 获取路径下文件列表** @param bucketName bucket名称* @param recursive  是否递归查找,如果是false,就模拟文件夹结构查找* @return 二进制流*/public static Iterable<Result<Item>> listObjects(String bucketName, boolean recursive) {return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).recursive(recursive).build());}/*** 删除文件** @param bucketName bucket名称* @param objectName 文件名称*/public static void removeObject(String bucketName, String objectName)throws Exception {minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());}/*** 批量删除文件** @param bucketName bucket* @param keys       需要删除的文件列表*/public static void removeObjects(String bucketName, List<String> keys) {List<DeleteObject> objects = new LinkedList<>();keys.forEach(s -> {objects.add(new DeleteObject(s));try {removeObject(bucketName, s);} catch (Exception e) {System.err.println("批量删除失败!");}});}/*** 生成预览链接,最大7天有效期;* 如果想永久有效,在 minio 控制台设置仓库访问规则总几率** @param object      文件名称* @param contentType 预览类型 image/gif", "image/jpeg", "image/jpg", "image/png", "application/pdf* @param validTime   有效时间 不能超过7天* @param timeUnit    单位 时 分 秒 天* @return java.lang.String**/public static String getPreviewUrl(String bucketName, String object, String contentType, Integer validTime, TimeUnit timeUnit) {Map<String, String> reqParams = null;if (contentType != null) {reqParams = new HashMap<>();reqParams.put("response-content-type", contentType != null ? contentType : "application/pdf");}String url = null;try {url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(bucketName).object(object).expiry(validTime, timeUnit).extraQueryParams(reqParams).build());} catch (Exception e) {e.printStackTrace();}return url;}/*** Description 文件列表** @param limit 范围 1-1000**/public List<Item> listObjects(int limit, String bucketName) {List<Item> objects = new ArrayList<>();Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).maxKeys(limit).includeVersions(true).build());try {for (Result<Item> result : results) {objects.add(result.get());}} catch (Exception e) {e.printStackTrace();}return objects;}/*** Description 网络文件转储 minio** @param httpUrl 文件地址**/public static void netToMinio(String httpUrl, String bucketName) {int i = httpUrl.lastIndexOf(".");String substring = httpUrl.substring(i);URL url;try {url = new URL(httpUrl);URLConnection urlConnection = url.openConnection();// agent 模拟浏览器urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");DataInputStream dataInputStream = new DataInputStream(url.openStream());// 临时文件转储File tempFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), substring);FileOutputStream fileOutputStream = new FileOutputStream(tempFile);ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int length;while ((length = dataInputStream.read(buffer)) > 0) {output.write(buffer, 0, length);}fileOutputStream.write(output.toByteArray());// 上传minioputObject(bucketName, tempFile.getAbsolutePath(), tempFile.getName());dataInputStream.close();fileOutputStream.close();} catch (Exception e) {e.printStackTrace();}}/*** Description 文件转字节数组** @param path 文件路径* @return byte[] 字节数组**/public byte[] fileToBytes(String path) {FileInputStream fis = null;ByteArrayOutputStream bos = null;try {bos = new ByteArrayOutputStream();fis = new FileInputStream(path);int temp;byte[] bt = new byte[1024 * 10];while ((temp = fis.read(bt)) != -1) {bos.write(bt, 0, temp);}bos.flush();} catch (IOException e) {e.printStackTrace();} finally {try {if (Objects.nonNull(fis)) {fis.close();}} catch (IOException e) {e.printStackTrace();}}return bos.toByteArray();}/*** 将URLDecoder编码转成UTF8*/public static String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");return URLDecoder.decode(url, "UTF-8");}/*** 下载并压缩 Minio 桶中的文件,并通过 HTTP 响应输出** @param bucketName 桶名称* @param response   HTTP 响应对象*/public static void downloadMinioFileToZip(String bucketName, HttpServletResponse response) {downloadMinioFileToZip(bucketName, "", response);}/*** 下载并压缩 Minio 桶中的文件,并通过 HTTP 响应输出** @param bucketName 桶名称* @param folderPath 文件夹路径(可为空)* @param response   HTTP 响应对象*/public static void downloadMinioFileToZip(String bucketName, String folderPath, HttpServletResponse response) {try {// 如果 folderPath 为空,列出整个桶中的文件if (folderPath == null || folderPath.isEmpty()) {// 根目录folderPath = "";}// 设置 HTTP 响应头response.setContentType("application/zip");response.setHeader("Content-Disposition", "attachment;filename=" + bucketName + ".zip");// 创建 ZipOutputStream,将文件写入 response 的输出流try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {// 列出文件夹中的所有对象Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(folderPath).recursive(true).build());// 下载并压缩文件夹中的所有对象for (Result<Item> result : results) {Item item = result.get();String objectName = item.objectName();log.info("找到对象: {}", objectName);// 跳过目录对象,确保只处理实际文件if (objectName.endsWith("/")) {continue;}// 为每个对象创建一个新的 ZipEntry(压缩包中的文件条目)ZipEntry zipEntry = new ZipEntry(objectName);zipOut.putNextEntry(zipEntry);// 从 MinIO 获取对象输入流try (InputStream stream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build())) {// 将文件数据写入压缩包byte[] buf = new byte[8192];int bytesRead;while ((bytesRead = stream.read(buf)) != -1) {zipOut.write(buf, 0, bytesRead);}// 关闭当前文件条目zipOut.closeEntry();log.info("文件压缩成功: {}", objectName);} catch (Exception e) {log.error("下载并压缩文件时发生错误: {}", e.getMessage(), e);}}log.info("所有文件已成功压缩并通过响应输出。");} catch (IOException e) {log.error("创建压缩包时发生错误: {}", e.getMessage(), e);}} catch (MinioException | InvalidKeyException | NoSuchAlgorithmException e) {log.error("发生错误: {}", e.getMessage(), e);}}}
配置类:
import com.saas.iot.utils.MinioUtils;
import io.minio.MinioClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfig {@Resourceprivate MinioProperties minioProperties;@Beanpublic MinioClient minioClient() {return MinioClient.builder().endpoint(minioProperties.getUrl()).credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey()).build();}@Beanpublic MinioUtils creatMinioClient() {return new MinioUtils(minioProperties.getUrl(), minioProperties.getAccessKey(), minioProperties.getSecretKey());}}
测试接口实现类:
请求接口:
    /*** 文件上传请求*/@PostMapping("upload")@ApiOperation("文件上传")public R upload(MultipartFile file) {return R.ok(sysFileService.uploadFile(file));}
服务层接口方法:
    /*** 文件上传接口** @param file 上传的文件* @return 访问地址* @throws Exception*/String uploadFile(MultipartFile file) throws Exception;
实现方法:
    @Overridepublic String uploadFile(MultipartFile file) throws Exception {if (file.isEmpty() || file.getSize() <= 0 || StrUtil.isBlank(file.getOriginalFilename())) {throw new RuntimeException("上传文件不能为空");}String originalFilename = file.getOriginalFilename();// 定义支持格式文件String[] defaultAllowedExtension = MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION;Set<String> typeSet = new HashSet<>(Arrays.asList(defaultAllowedExtension));originalFilename = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);if (!typeSet.contains(originalFilename)){throw new RuntimeException("文件格式不支持");            }ObjectWriteResponse response = MinioUtils.putObject(minioConfig.getBucket(), file, getFileName(originalFilename), file.getContentType());return minioConfig.getAccessUrl() + minioConfig.getBucket() + "/" + response.object();}/*** 自定义文件名称*/private String getFileName(String suffix) {// 不同的后缀分为一组 data/local/jpg/xxx.jpgreturn "data/local/" + suffix + "/" + IdUtil.getSnowflake() + "." + suffix;}
定义系统允许文件类型:
    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",//升级文件"bin", "apk", "ipa",// 视频格式"mp4", "avi", "rmvb",// 矢量文件"tif",// pdf"pdf" };
关键字:中国跨境电商出口平台_邢台有限公司_国外域名购买_大连网站建设费用

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: