minio和kkfileview的docker部署方案就不在这边说明了,搜索博客可以得到答案
ymlkkfileview: http://127.0.0.1:8012/onlinePreview?url=
# Minio配置
minio:
url: http://8.129.231.12:9000
accessKey: minioadmin
secretKey: minioadmin
bucketName: test
javaimport org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.minio.MinioClient;
/**
* Minio 配置信息
*
* @author haowee
*/
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig
{
/**
* 服务地址
*/
private String url;
/**
* 用户名
*/
private String accessKey;
/**
* 密码
*/
private String secretKey;
/**
* 存储桶名称
*/
private String bucketName;
/**
* kkfileview预览文件前缀地址
*/
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;
}
@Bean
public MinioClient getMinioClient()
{
return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
}
}
javapackage com.haowee.file.config;
import com.haowee.common.core.utils.sign.Base64;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "kkfileview")
public class KkFileViewConfig {
private String prefix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getKkFileViewUrl(String fileUrl){
String urlBase64= Base64.encode(fileUrl.getBytes());
return getPrefix()+urlBase64;
}
}
javapackage com.haowee.file.controller;
import com.haowee.common.core.domain.R;
import com.haowee.common.core.utils.StringUtils;
import com.haowee.common.core.utils.file.FileUtils;
import com.haowee.file.service.ISysFileService;
import com.haowee.system.api.domain.SysFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
/**
* 文件请求处理
*
* @author haowee
*/
@RestController
public class SysFileController
{
private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
@Autowired
private ISysFileService sysFileService;
/**
* 文件上传请求
*/
@PostMapping("upload")
public R<SysFile> upload(MultipartFile file)
{
try
{
// 上传并返回访问地址
String url = sysFileService.uploadFile(file);
SysFile sysFile = new SysFile();
sysFile.setName(FileUtils.getName(url));
sysFile.setUrl(url);
return R.ok(sysFile);
}
catch (Exception e)
{
log.error("上传文件失败", e);
return R.fail(e.getMessage());
}
}
/**
* 下载文件
*
* @param fileUrl 文件地址
*
*/
@GetMapping("download")
public void download(String fileUrl, HttpServletResponse response) {
sysFileService.downloadFile(fileUrl, response);
}
/**
* 下载文件
*
* @param fileUrl 文件地址
*
*/
@GetMapping("downloadByRes")
public ResponseEntity<Resource> downloadByRes(String fileUrl) {
return sysFileService.downloadFile(fileUrl);
}
/**
* 删除文件
*
* @param fileUrl 文件地址
*
*/
@DeleteMapping("delete")
public R delete(String fileUrl){
boolean result= sysFileService.deleteFile(fileUrl);
if (result){
return R.ok();
}else {
return R.fail();
}
}
/**
* 获取文件预览地址
*
* @param fileUrl 文件地址
*
*/
@GetMapping("presignedUrl")
public R<String> getPresignedUrl(String fileUrl){
String url=sysFileService.getPresignedUrl(fileUrl);
if (StringUtils.isNotBlank(url)){
return R.ok(url);
}else {
return R.fail();
}
}
}
javapackage com.haowee.file.service;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
/**
* 文件上传接口
*
* @author haowee
*/
public interface ISysFileService
{
/**
* 文件上传接口
*
* @param file 上传的文件
* @return 访问地址
* @throws Exception
*/
public String uploadFile(MultipartFile file) throws Exception;
/**
* 下载文件
*
* @param fileUrl 文件地址
* @param
*/
void downloadFile(String fileUrl,HttpServletResponse response);
/**
* 删除文件
*
* @param fileUrl 文件地址
*/
boolean deleteFile(String fileUrl);
/**
* 获取文件预览url
*
* @param fileUrl 文件地址
* @return
*/
String getPresignedUrl(String fileUrl);
ResponseEntity<Resource> downloadFile(String fileUrl);
}
javapackage com.haowee.file.service;
import com.alibaba.nacos.common.utils.IoUtils;
import com.haowee.common.core.utils.StringUtils;
import com.haowee.file.config.KkFileViewConfig;
import com.haowee.file.config.MinioConfig;
import com.haowee.file.utils.FileUploadUtils;
import io.minio.*;
import io.minio.http.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
/**
* Minio 文件存储
*
* @author haowee
*/
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{
@Autowired
private MinioConfig minioConfig;
@Autowired
private MinioClient client;
@Autowired
private KkFileViewConfig kkFileViewConfig;
private static final Logger log = LoggerFactory.getLogger(MinioSysFileServiceImpl.class);
/**
* Minio文件上传接口
*
* @param file 上传的文件
* @return 访问地址
* @throws Exception
*/
@Override
public 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;
}
@Override
public void downloadFile(String fileUrl,HttpServletResponse response) {
String fileDir = getFileDir(fileUrl);
if (StringUtils.isBlank(fileDir)) {
log.error("文件内容为空!");
return;
}
try {
// 获取文件流
InputStream file = client.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileDir).build());
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(fileUrl.substring(fileUrl.lastIndexOf("/") + 1), String.valueOf(StandardCharsets.UTF_8)));
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
// 获取输出流
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();
log.info("文件{}下载成功", fileDir);
} catch (Exception e) {
log.error("文件名: " + fileDir + "下载文件时出现异常: " + e);
}
}
@Override
public ResponseEntity<Resource> downloadFile(String fileUrl) {
try {
// 获取文件路径
String fileDir = getFileDir(fileUrl);
// 获取文件输入流
InputStream file = client.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileDir).build());
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUrl.substring(fileUrl.lastIndexOf("/") + 1), StandardCharsets.UTF_8.toString()));
headers.add("Content-Type", "application/octet-stream");
// 返回 ResponseEntity
return ResponseEntity.ok()
.headers(headers)
.body(new InputStreamResource(file));
} catch (Exception e) {
log.error("下载文件时出现异常: " + e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* 删除文件
*
* @param fileUrl 文件路径
*/
@Override
public boolean deleteFile(String fileUrl) {
// 获取桶名
String bucketName = minioConfig.getBucketName();
try {
String fileDir=getFileDir(fileUrl);
if (StringUtils.isBlank(fileDir)) {
log.error("删除文件失败,文件名为空!");
return false;
}
// 判断桶是否存在
boolean isExist = client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
// 桶存在
if (isExist) {
client.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileDir).build());
return true;
} else { // 桶不存在
log.error("删除文件失败,桶{}不存在", bucketName);
return false;
}
} catch (Exception e) {
log.error("删除文件时出现异常: " + e.getMessage());
return false;
}
}
/**
* 获取文件预览url
*
* @param fileUrl 文件名
* @return 文件预览url
*/
@Override
public String getPresignedUrl(String fileUrl) {
// 获取桶名
String bucketName = minioConfig.getBucketName();
String presignedUrl = null;
try {
String fileDir=getFileDir(fileUrl);
if (StringUtils.isBlank(fileDir)) {
log.error("获取文件预览url失败,文件名为空!");
return presignedUrl;
}
// 判断桶是否存在
boolean isExist = client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
// 桶存在
if (isExist) {
presignedUrl = client.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
.method(Method.PUT)
.bucket(bucketName)
.object(fileDir)
.expiry(1, TimeUnit.DAYS) // 一天过期时间
.build());
return presignedUrl;
//默认的文件预览只支持pdf,如果需要更多格式请用kkFileView
// return kkFileViewConfig.getKkFileViewUrl(presignedUrl);
} else { // 桶不存在
log.error("获取文件预览url失败,桶{}不存在", bucketName);
}
} catch (Exception e) {
log.error("获取文件预览url时出现异常: " + e.getMessage());
}
return presignedUrl;
}
/**
* 这个文件目录是存储桶名称之后的路径内容
* @param fileUrl
* @return
*/
private String getFileDir(String fileUrl){
String fileDir=fileUrl.split(minioConfig.getBucketName())[1].substring(1);
return fileDir;
}
}
本文作者:Weee
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!