此处先将图片下载到本地,再进行转换
MinIO是一个对象存储服务,非常轻量
Java Api
依赖:
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>3.0.10</version>
</dependency>
java api 通过一个http客户端进行存储和获取对象文件,所以java代码中可以通过以下的步骤进行存储和获取:
//1 实例化一个MinioClient客户端:
MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);
//2 创建存储桶bucket:
String bucket = "demo-bucket";
boolean isExist = minioClient.bucketExists(bucket);
if(isExist) {
LOGGER.info("Bucket {} already exists.", bucket);
} else {
minioClient.makeBucket(bucket);
}
//3 存储文件对象(需要指定存储的桶):
minioClient.putObject(bucket, destFileName, file.getAbsolutePath());
//因为MinioClient使用http客户端,并不是长连接,所以不需要进行关闭连接和释放资源的操作。
//至此,文件已经存储完毕,可以在Minio服务器查询看到,bucket中的文件
//4 获取对象文件如下(获取输入流InputStream):
public InputStream getStream(String bucket, String fileName) {
InputStream is = null;
try {
MinioClient minioClient = ...; // 再实例化一个客户端
is = minioClient.getObject(bucket, fileName);
} catch(MinioException | NoSuchAlgorithmException | IOException | XmlPullParserException | InvalidKeyException e) {
LOGGER.error("error: {}", e.getMessage());
}
return is;
}
//如果需要获取File对象:
public File getFile(String bucket, String fileName) {
InputStream is = getStream(bucket, fileName);
File dir = new File(tmpDir);
if (!dir.exists() || dir.isFile()) {
dir.mkdirs();
}
File file = new File(tmpDir + fileName);
try {
FileUtils.copyToFile(is, file);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
//如果需要下载文件,可以直接将输入流写入servlet输出流即可:
public void writeTo(String bucket, String fileName, OutputStream os) throws IOException {
InputStream is = getStream(bucket, fileName);
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
os.flush();
}
项目使用小例
Controller
@Autowired
private ProjectImageAppService projectImageAppService;
@ResponseBody
@GetMapping(value = "/downloadProjectPhoto/{fileName}")
@ApiOperation(value = "下载项目图片返回base64")
public Result downloadProjectPhoto( @ApiParam(value = "下载项目图片", required = true) @PathVariable String fileName) {
String base64Image = projectImageAppService.downloadProjectPhoto(fileName);
if(StringUtils.isEmpty(base64Image)){
return Result.failure();
}else {
Map<String, Object> map = new HashMap<>();
map.put("imageBase64", base64Image);
return Result.success(map);
}
}
@ResponseBody
@PostMapping(value = "/createPhoto")
@ApiOperation(value = "添加报警数据图片报警")
public Result create(@ApiParam(value = "图片报警", required = true) @RequestParam(value = "base64")String base64,@RequestParam(value = "base64Array")String[] base64Array,@RequestParam(value = "uid")String uid) {
EmsAlert emsAlert = safetyMonitoringService.create(base64, base64Array, uid);
if (emsAlert == null) {
return Result.failure();
}
return Result.success();
}
@ResponseBody
@GetMapping(value = "/downloadPhoto/{fileName}")
@ApiOperation(value = "下载数据图片[可共用]")
public void download(HttpServletResponse response, HttpServletRequest request, @ApiParam(value = "下载图片报警", required = true) @PathVariable String fileName) {
safetyMonitoringService.download(response, fileName);
}
service
/**
* 下载项目图片
* @param fileName 项目图片名称
* @return 项目数据
*/
public String downloadProjectPhoto(@NotNull String fileName) {
try {
return minIoService.downloadPhotoBase64(fileName);
}catch (Exception e){
}
return null;
}
/**
* 添加报警数据
* @param base64 报警图片大图
* @param base64Array 报警图小图
* @param uid 识别码
* @return 报警数据
*/
public EmsAlert create(@NotNull String base64,String[] base64Array,String uid) {
String resourcePid = null;
try {
//上传
if (multipartFileUtils.base64ToMultipart(base64) != null){
String upload = minIoService.upload(multipartFileUtils.base64ToMultipart(base64));
if (upload.equals("") || upload.equals(null)){
return null;
}
}
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 下载报警图片
* @param fileName 报警图片名称
* @return 报警数据
*/
public void download(HttpServletResponse response, @NotNull String fileName) {
try {
minIoService.download(fileName,response);
}catch (Exception e){
}
}
MinIoService
package com.sjasoft.cloud.admin.service.ems;
import com.sjasoft.framework.spring.bean.Result;
import com.sjasoft.framework.spring.utils.minio.MinioUtils;
import io.minio.StatObjectResponse;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
import java.util.UUID;
/**
* MinIoService
* @version 1.0
*/
@Service
public class MinIoService {
@Autowired
private SafetyMonitoringService safetyMonitoringService;
@Value("${photo.path}")
private String localhostPath;
/**
* 下载文件
*/
public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
StatObjectResponse stat = MinioUtils.getObjectInfo(fileName);
InputStream in = MinioUtils.getObject(fileName);
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] b = swapStream.toByteArray();
if (b == null) {
return;
}
System.out.println("获取流" + b);
OutputStream out = response.getOutputStream();
out.write(b);
out.flush();
out.close();
}
/**
* 上传文件
* @param file
* @return
* @throws Exception Exception
*/
public String upload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
return null;
} else {
// 得到文件流
final InputStream is = file.getInputStream();
// 文件名
final String fileName = UUID.randomUUID().toString() +file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
// 把文件放到minio的boots桶里面
MinioUtils.putObject(fileName, is);
String objectUrl = MinioUtils.getBaseUrl() + fileName;
// 关闭输入流
is.close();
return fileName;
}
}
/**
* 删除文件
* @param fileName
* @return JsonResult
*/
public Result delete(@RequestParam("fileName") String fileName) throws Exception {
MinioUtils.removeObject(fileName);
return Result.success("删除成功");
}
/**
* 下载图片以base64方式返回
*/
public String downloadPhotoBase64(@RequestParam("fileName") String fileName) throws IOException {
StatObjectResponse stat = MinioUtils.getObjectInfo(fileName);
InputStream in = MinioUtils.getObject(fileName);
//转换为base64
byte[] bytes = IOUtils.toByteArray(in);
String encoded = Base64.getEncoder().encodeToString(bytes);
return encoded;
}
}
application.yml文件
server:
port: 9180
spring:
application:
name: cloud-admin
datasource:
url: jdbc:mysql://192.168.2.50:3306/ems?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: sjadba
password: dbadmin
druid:
#连接池初始化大小
initial-size: 5
#最小空闲连接数
min-idle: 10
#最大连接数
max-active: 20
web-stat-filter:
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #不统计这些请求数据
#访问监控网页的登录用户名和密码
stat-view-servlet:
login-username: druid
login-password: druid
jwt:
#JWT存储的请求头
authHeader: Authorization
#JWT负载中的认证模式
authSchema: Bearer
#JWT加解密使用的密钥
secret: cloud-admin-secret
#JWT的超期限时间(60*60*24=86400)
expiration: 86400
eureka:
client:
service-url:
defaultZone: http://localhost:9101/eureka/
mybatis:
mapper-locations:
- classpath:com/**/dao/*.xml
- classpath*:com/**/mapper/*.xml
mapper:
mappers: com.sjasoft.framework.spring.mybatis.dao.BaseDao
not-empty: false
identity: select replace(uuid(), ''-'', '''')
before: true
secure:
ignored:
#安全路径白名单
urls:
- /swagger-ui.html
- /swagger-resources/**
- /swagger/**
- /**/v2/api-docs
- /**/*.js
- /**/*.css
- /**/*.png
- /**/*.ico
- /webjars/springfox-swagger-ui/**
- /actuator/**
- /druid/**
- /user/login
- /user/register
- /user/info
- /user/logout
- /doc.html
- /websocket
- /ems/safetyMonitoring/downloadPhoto
mina:
port: 9011
## minio文件系统
minio:
endpoint: http://192.168.2.50:9000 #MinIO服务所在地址
bucketName: test #存储桶名称
accessKey: sja-soft #访问的key
secretKey: sja.1234 #访问的秘钥
photo:
path: D:/photoPath
#这两个密钥在极光官网申请获得
jpush:
appKey: 5b31439dbd41e33ee9115fd8
masterSecret: 422fa52342fa7cab6e518c80
liveTime: 1000
# 组织表中图片前缀
orgImage:
imagePrefix: E://360Downloads/testImage/
# 亚洲时区
time:
zone: Asia/Shanghai
# 服务器的时序数据库
InfluxDBConnection:
url: http://192.168.2.50:8086
username: csems
password: qaz123/*-+
# 数据库名
dataBaseName: eam-buildingsite