赞
踩
先看几个常用的docker命令:
systemctl start docker 启动docker服务
docker stop [id] 停止容器
docker rm [id] 删除容器
docker ps -a 所有容器
docker ps 所有运行的容器
docker images 查看镜像
docker image rm [img_id] 删除镜像
docker logs [img_id] 查看日志
最新版的minio配置比较麻烦,个人用旧版的方便一些
docker pull minio/minio:RELEASE.2021-06-17T00-10-46Z
docker run -p 9000:9000 --name minio -di --restart=always \
-e "MINIO_ROOT_USER=minioadmin" \
-e "MINIO_ROOT_PASSWORD=minioadmin" \
-v /usr/local/minio/data:/data \
-v /usr/local/minio/config:/root/.minio \
minio/minio:RELEASE.2021-06-17T00-10-46Z server /data
注意:第二、三行的minioadmin
是账号和密码
ip:9000登录之后。
创建之后:
这样就可以了
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.3</version>
</dependency>
minio:
endpoint: http://127.0.0.1:9000 #Minio服务所在地址
#bucketName: tulaoda #存储桶名称 可以不在这里设置
accessKey: minioadmin #访问的key
secretKey: minioadmin #访问的秘钥
import io.minio.MinioClient; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Data @Component public class MinIoClientConfig { @Value("${minio.endpoint}") private String endpoint; @Value("${minio.accessKey}") private String accessKey; @Value("${minio.secretKey}") private String secretKey; @Bean public MinioClient minioClient() { return MinioClient.builder() .endpoint(endpoint) .credentials(accessKey, secretKey) .build(); } }
先加一个实体类:
import lombok.Data;
@Data
public class ObjectItem {
private String objectName;
private Long size;
}
import cn.sd.bzu.domain.ObjectItem; import io.minio.*; import io.minio.errors.*; import io.minio.http.Method; import io.minio.messages.DeleteError; import io.minio.messages.DeleteObject; import io.minio.messages.Item; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Component public class MinioUtils { @Autowired private MinioClient minioClient; public void existBucket(String name) { try { boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build()); if (!exists) { minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build()); } } catch (Exception e) { e.printStackTrace(); } } /** * 创建存储bucket * * @param bucketName 存储bucket名称 * @return Boolean */ public Boolean makeBucket(String bucketName) { try { minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 删除存储bucket * * @param bucketName 存储bucket名称 * @return Boolean */ public Boolean removeBucket(String bucketName) { try { minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build()); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * description: 上传文件 * * @param multipartFile * @return: java.lang.String */ public List<String> upload(MultipartFile[] multipartFile, String bucketName) { List<String> names = new ArrayList<>(multipartFile.length); for (MultipartFile file : multipartFile) { String fileName = file.getOriginalFilename(); String[] split = fileName.split("\\."); if (split.length > 1) { fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1]; } else { fileName = fileName + System.currentTimeMillis(); } InputStream in = null; try { in = file.getInputStream(); minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(in, in.available(), -1).contentType(file.getContentType()).build()); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } names.add(fileName); } return names; } /** * description: 设置分享连接 * * @param * @return: String */ public String presignedGetObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException, ServerException { BucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build(); boolean bucketExists = minioClient.bucketExists(bucketArgs); // boolean flag = bucketExists(bucketName); String url = ""; if (bucketExists) { try { if (expires == null) { expires = 604800; } GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(bucketName).object(objectName) // .expiry(expires) .build(); url = minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs); System.out.println("*******url2:{}" + url); } catch (Exception e) { System.out.println("presigned get object fail:{}" + e); } } return url; } /** * description: 下载文件 * * @param fileName * @return: org.springframework.http.ResponseEntity<byte [ ]> */ public ResponseEntity<byte[]> download(String fileName, String bucketName) { ResponseEntity<byte[]> responseEntity = null; InputStream in = null; ByteArrayOutputStream out = null; try { in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build()); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); //封装返回值 byte[] bytes = out.toByteArray(); HttpHeaders headers = new HttpHeaders(); try { headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } headers.setContentLength(bytes.length); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setAccessControlExposeHeaders(Arrays.asList("*")); responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return responseEntity; } /** * 查看文件对象 * * @param bucketName 存储bucket名称 * @return 存储bucket内文件对象信息 */ public List<ObjectItem> listObjects(String bucketName) { Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build()); List<ObjectItem> objectItems = new ArrayList<>(); try { for (Result<Item> result : results) { Item item = result.get(); ObjectItem objectItem = new ObjectItem(); objectItem.setObjectName(item.objectName()); objectItem.setSize(item.size()); objectItems.add(objectItem); } } catch (Exception e) { e.printStackTrace(); return null; } return objectItems; } /** * 批量删除文件对象 * * @param bucketName 存储bucket名称 * @param objects 对象名称集合 */ public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) { List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList()); Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build()); return results; } /** * description: 上传文件 * * @param multipartFile * @return: java.lang.String */ public List<String> uploadLive(MultipartFile[] multipartFile, String bucketName, String fileName) { List<String> names = new ArrayList<>(multipartFile.length); for (MultipartFile file : multipartFile) { fileName = fileName + ".jpg"; InputStream in = null; try { in = file.getInputStream(); minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(in, in.available(), -1).contentType(file.getContentType()).build()); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } names.add(fileName); } return names; } }
至于这个,看个样例吧
@Value("${minio.endpoint}") private String endpoint; @Autowired MinioUtils minioUtils; @RequestMapping(name = "/",method = RequestMethod.POST) public String videoAdd(CourseInfo courseInfo, Model model, MultipartFile[] file) { courseInfo.setCourseFrom(endpoint + "/video/"+file[0].getOriginalFilename()); courseInfo.setCourseCover(endpoint + "/image/"+file[1].getOriginalFilename()); List<String> upload= minioUtils.upload(new MultipartFile[]{file[0]},"video"); courseInfo.setCourseFrom(endpoint + "/video/"+upload.get(0)); upload = minioUtils.upload(new MultipartFile[]{file[1]},"image"); courseInfo.setCourseCover(endpoint + "/image/"+upload.get(0)); if(courseInfoService.Insert_Course(courseInfo) != 0 && upload != null) { model.addAttribute("videoMsg",1); // 视频添加成功 } else { model.addAttribute("videoMsg",2); // 视频添加失败 } return "redirect:/admin/video/videoList"; }
或者:
@Value("${minio.endpoint}") private String endpoint; @Autowired MinioUtils minioUtils; @Log(title = "多图片上传", businessType = BusinessType.UPDATE) @PostMapping("/multiPicturesUpload") public AjaxResult multiPicturesUpload(MultipartFile file,int competitionId) throws IOException{ String filename = file.getOriginalFilename(); List<String> upload = minioUtils.upload(new MultipartFile[]{file}, "competitionimg"); AjaxResult ajax = AjaxResult.success(); String url = endpoint + "/competitionimg/" + upload.get(0); ajax.put("fileName", url); return ajax; }
删除样例:
@DeleteMapping("/{fileUrl}")
public AjaxResult removeByUrl(@PathVariable String fileUrl) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
List<String> objects = new ArrayList<>();
objects.add(fileUrl);
Iterable<Result<DeleteError>> results = minioUtils.removeObjects(FileConfig.competitionFile, objects);
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
System.out.println(
"Error in deleting object " + error.objectName() + "; " + error.message());
}
return toAjax(competitionFileInfoService.deleteCompetitionFileInfoByFileUrl(fileUrl));
}
在removeObjects后,需要对结果进行迭代
参考:https://www.jianshu.com/p/ca93e289d579
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。