本文主要是介绍MinIo - java代码 实现图片上传至Minio桶,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MinIO是一款开源的高性能、可伸缩、安全的对象存储系统,专为云原生和容器化环境而设计
(基于minio已经集成在服务器中)
第一步,毫无疑问肯定是创建一个桶(用于存放的容器)
这个Name根据自己的需求自定义
然后点击Create Bucket
可以看见新创建的桶已经完成
点击新创建的桶,然后可以看见详情页面,的Access Policy是Private,我们需要修改这个状态
修改为Public
Set保存
然后需要获取权限码Access Keys
点击+创建access Keys
可以看见出现Access key 和 Secret Key
复制Access key 和 Secret Key到Nacos相对应的配置文件中
# Minio配置
minio:url: http://你的服务器ip:9001accessKey: 生成的accessKeysecretKey: 生成的secretKeybucketName: 桶名称
然后开始写代码,这里我使用的是工厂模式,我就给minio的代码放在下面,可以直接复制使用,工具类放在最后
@PostMapping("upload")public String upload(MultipartFile file){try{// 上传并返回访问地址String url = sysFileService.uploadFile(file);SysFile sysFile = new SysFile();sysFile.setName(FileUtils.getName(url));sysFile.setUrl(url);return url ;}catch (Exception e){log.error("上传文件失败", e);return "上传文件失败";}}
接口
/*** 文件上传接口** @author Rui*/
public interface ISysFileService
{/*** 文件上传接口** @param file 上传的文件* @return 访问地址* @throws Exception*/String uploadFile(MultipartFile file) throws Exception;
}
/*** Minio 文件存储** @author Rui*/
@Primary
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{@Autowiredprivate MinioConfig minioConfig;@Autowiredprivate MinioClient client;/*** Minio文件上传接口** @param file 上传的文件* @return 访问地址* @throws Exception*/@Overridepublic String uploadFile(MultipartFile file) throws Exception{String fileName = FileUploadUtils.extractFilename(file);InputStream inputStream = file.getInputStream();PutObjectArgs args = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).stream(inputStream, file.getSize(), -1).contentType(file.getContentType()).build();client.putObject(args);IoUtils.closeQuietly(inputStream);return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;}
相关minio 的config
/*** Minio 配置信息** @author Rui*/
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig
{/*** 服务地址*/private String url;/*** 用户名*/private String accessKey;/*** 密码*/private String secretKey;/*** 存储桶名称*/private String bucketName;public String getUrl(){return url;}public void setUrl(String url){this.url = url;}public String getAccessKey(){return accessKey;}public void setAccessKey(String accessKey){this.accessKey = accessKey;}public String getSecretKey(){return secretKey;}public void setSecretKey(String secretKey){this.secretKey = secretKey;}public String getBucketName(){return bucketName;}public void setBucketName(String bucketName){this.bucketName = bucketName;}@Beanpublic MinioClient getMinioClient(){return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();}
}
这个是utils
/*** 文件上传工具类** @author RUi*/
public class FileUploadUtils
{/*** 默认大小 50M*/public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;/*** 默认的文件名最大长度 100*/public static final int DEFAULT_FILE_NAME_LENGTH = 100;/*** 根据文件路径上传** @param baseDir 相对应用的基目录* @param file 上传的文件* @return 文件名称* @throws IOException*/public static final String upload(String baseDir, MultipartFile file) throws IOException{try{return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);}catch (FileException fe){throw new IOException(fe.getDefaultMessage(), fe);}catch (Exception e){throw new IOException(e.getMessage(), e);}}/*** 文件上传** @param baseDir 相对应用的基目录* @param file 上传的文件* @param allowedExtension 上传文件类型* @return 返回上传成功的文件名* @throws FileSizeLimitExceededException 如果超出最大大小* @throws FileNameLengthLimitExceededException 文件名太长* @throws IOException 比如读写文件出错时* @throws InvalidExtensionException 文件校验异常*/public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,InvalidExtensionException{int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH){throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);}assertAllowed(file, allowedExtension);String fileName = extractFilename(file);String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();file.transferTo(Paths.get(absPath));return getPathFileName(fileName);}/*** 编码文件名*/public static final String extractFilename(MultipartFile file){return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), FileTypeUtils.getExtension(file));}private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException{File desc = new File(uploadDir + File.separator + fileName);if (!desc.exists()){if (!desc.getParentFile().exists()){desc.getParentFile().mkdirs();}}return desc.isAbsolute() ? desc : desc.getAbsoluteFile();}private static final String getPathFileName(String fileName) throws IOException{String pathFileName = "/" + fileName;return pathFileName;}/*** 文件大小校验** @param file 上传的文件* @throws FileSizeLimitExceededException 如果超出最大大小* @throws InvalidExtensionException 文件校验异常*/public static final void assertAllowed(MultipartFile file, String[] allowedExtension)throws FileSizeLimitExceededException, InvalidExtensionException{long size = file.getSize();if (size > DEFAULT_MAX_SIZE){throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);}String fileName = file.getOriginalFilename();String extension = FileTypeUtils.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);}}}/*** 判断MIME类型是否是允许的MIME类型** @param extension 上传文件类型* @param allowedExtension 允许上传文件类型* @return true/false*/public static final boolean isAllowedExtension(String extension, String[] allowedExtension){for (String str : allowedExtension){if (str.equalsIgnoreCase(extension)){return true;}}return false;}
}
直接调用接口完成图片上传即可在桶中查看
这篇关于MinIo - java代码 实现图片上传至Minio桶的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!