切换OSS为阿里云OSS,文件上传成功,文件访问还有问题

This commit is contained in:
starrySky
2024-03-23 23:11:48 +08:00
parent 0fb5cc8145
commit 92d239286e
16 changed files with 251 additions and 296 deletions

View File

@@ -24,7 +24,7 @@ public class MyTenantLineHandler implements TenantLineHandler {
/**
* 排除过滤的表
*/
private static final String[] TABLE_FILTER = {"sys_menu", "sys_tenant_package", "sys_tenant", "sys_dict", "sys_dict_data"};
private static final String[] TABLE_FILTER = {"sys_user", "sys_menu", "sys_tenant_package", "sys_tenant", "sys_dict", "sys_dict_data"};
/**
* 排除过滤的表前缀
@@ -38,6 +38,9 @@ public class MyTenantLineHandler implements TenantLineHandler {
if (StrUtil.isBlankIfStr(tenantId)) {
return new NullValue();
}
if (StrUtil.isBlankIfStr(tenantId)) {
tenantId = "9999";
}
return new StringValue(tenantId);
}

View File

@@ -0,0 +1,34 @@
package com.starry.admin.common.oss;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Data
@Configuration
@ConfigurationProperties(prefix = "aliyun")
@PropertySource(value = {"classpath:oss.properties"})
public class OssProperties implements InitializingBean {
public String endpoint;
public String accessKeyId;
public String accessKeySecret;
public String bucketName;
public static String ENDPOINT = "";
public static String KEY_ID = "";
public static String KEY_SECRET = "";
public static String BUCKET_NAME = "";
@Override
public void afterPropertiesSet() throws Exception {
ENDPOINT = getEndpoint();
KEY_ID = getAccessKeyId();
KEY_SECRET = getAccessKeySecret();
BUCKET_NAME = getBucketName();
}
}

View File

@@ -0,0 +1,49 @@
package com.starry.admin.common.oss.controller;
import com.starry.admin.common.oss.service.IOssFileService;
import com.starry.common.result.R;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* @author admin
* cos存储前端控制器
* @since 2022/11/13 17:51
*/
@Slf4j
@RestController
@RequestMapping("/cos")
public class CosController {
@Resource
IOssFileService ossFileService;
@ApiOperation(value = "照片上传")
@PostMapping("/upload/image")
public R uploadImage(MultipartFile file) throws Exception {
if (!file.isEmpty()) {
String house = ossFileService.upload(file.getInputStream(), "house", file.getOriginalFilename());
return R.ok(house);
}
return R.error("上传照片异常,请联系管理员");
}
@ApiOperation(value = "获取cos临时密钥")
@GetMapping("/temp-key")
public R getTempKey() throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\admin\\Pictures\\0001.jpg"));
ossFileService.upload(inputStream, "test", "0001.png");
return R.ok();
}
}

View File

@@ -0,0 +1,23 @@
package com.starry.admin.common.oss.service;
import java.io.InputStream;
public interface IOssFileService {
/**
* 文件上传阿里云
*
* @param inputStream InputStream
* @param module String
* @param originalFilename 文件名称
*/
String upload(InputStream inputStream, String module, String originalFilename);
/**
* 删除文件
*
* @param url 文件地址
*/
void remove(String url);
}

View File

@@ -0,0 +1,98 @@
package com.starry.admin.common.oss.service.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.common.oss.OssProperties;
import com.starry.admin.common.oss.service.IOssFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import java.io.InputStream;
@Service
@Slf4j
public class OssFileServiceImpl implements IOssFileService {
@Override
public String upload(InputStream inputStream, String module, String filename) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
log.info("OSSClient实例创建成功");
try {
//判断oss实例是否存在如果不存在则创建如果存在则获取
if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)) {
//创建bucket
ossClient.createBucket(OssProperties.BUCKET_NAME);
log.info("bucket存储空间【{}】创建成功", OssProperties.BUCKET_NAME);
//设置oss实例的访问权限公共读
ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
log.info("【{}】存储空间访问权限设置为公共读成功", OssProperties.BUCKET_NAME);
}
//构建日期路径avatar/2019/02/26/文件名
String folder = new DateTime().toString("yyyy/MM/dd");
//文件名uuid.扩展名
filename = IdUtil.fastSimpleUUID() + FileTypeUtil.getType(inputStream);
//文件根路径
String key = module + "/" + folder + "/" + filename;
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(OssProperties.BUCKET_NAME, key, inputStream);
// 创建PutObject请求。
ossClient.putObject(putObjectRequest);
log.info("oss文件上传成功");
//阿里云文件绝对路径
String endpoint = OssProperties.ENDPOINT.substring(OssProperties.ENDPOINT.lastIndexOf("//") + 2);
//返回文件的访问路径
return "https://" + OssProperties.BUCKET_NAME + "." + endpoint + "/" + key;
} catch (OSSException oe) {
log.error("OSSException 文件上传失败:", oe);
throw new CustomException("OSS文件上传异常,{}" + oe.getMessage());
} catch (ClientException ce) {
log.error("ClientException 文件上传失败:{}", ExceptionUtils.getStackTrace(ce));
throw new CustomException("OSS文件上传异常,{}" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
log.info("关闭ossClient");
}
}
}
@Override
public void remove(String url) {
OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
log.info("OSSClient实例创建成功");
try {
String endpoint = OssProperties.ENDPOINT.substring(OssProperties.ENDPOINT.lastIndexOf("//") + 2);
//文件名(服务器上的文件路径)
String host = "https://" + OssProperties.BUCKET_NAME + "." + endpoint + "/";
String objectName = url.substring(host.length());
// 删除文件或目录。如果要删除目录,目录必须为空。
ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
log.info("{}文件删除成功", objectName);
} catch (OSSException oe) {
log.error("OSSException 文件删除失败", oe);
throw new CustomException("OSS文件删除异常,{}" + oe.getMessage());
} catch (ClientException ce) {
log.error("ClientException 文件删除失败:{}", ExceptionUtils.getStackTrace(ce));
throw new CustomException("OSS文件删除异常,{}" + ce.getMessage());
} finally {
if (ossClient != null) {
// 关闭OSSClient。
ossClient.shutdown();
log.info("关闭ossClient");
}
}
}
}

View File

@@ -4,6 +4,7 @@ package com.starry.admin.modules.system.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starry.admin.common.component.JwtToken;
import com.starry.admin.common.domain.LoginUser;
import com.starry.admin.common.oss.service.IOssFileService;
import com.starry.admin.modules.system.entity.SysRoleEntity;
import com.starry.admin.modules.system.entity.SysUserEntity;
import com.starry.admin.modules.system.service.SysRoleService;
@@ -14,7 +15,6 @@ import com.starry.common.annotation.Log;
import com.starry.common.constant.UserConstants;
import com.starry.common.enums.BusinessType;
import com.starry.common.result.R;
import com.starry.common.utils.file.CosClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
@@ -47,6 +47,9 @@ public class SysUserController {
@Resource
private JwtToken tokenService;
@Resource
private IOssFileService ossFileService;
@ApiOperation(value = "注册用户")
@PostMapping(value = "register")
public R register(@RequestBody SysUserEntity user) {
@@ -133,7 +136,7 @@ public class SysUserController {
@PostMapping("/profile/avatar")
public R uploadAvatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
if (!file.isEmpty()) {
String avatar = CosClientUtils.upload(file, "avatar");
String avatar = ossFileService.upload(file.getInputStream(), "avatar", file.getOriginalFilename());
if (userService.updateUserAvatar(SecurityUtils.getUserId(), avatar)) {
// 更新缓存用户头像
LoginUser loginUser = SecurityUtils.getLoginUser();

View File

@@ -90,13 +90,4 @@ xl:
authCode:
# 登录验证码是否开启开发环境配置false方便测试
enable: false
# 腾讯云cos配置
cos:
baseUrl: https://admin-125966.cos.ap-guangzhou.myqcloud.com
secretId: AKIDdHsLgtxoSs3sWw73lz
secretKey: zZxBD0b4QcZGmdFcotm
regionName: ap-guangzhou
bucketName: admin-125966
folderPrefix: /upload

View File

@@ -85,12 +85,4 @@ xl:
login:
authCode:
# 登录验证码是否开启开发环境配置false方便测试
enable: false
# 腾讯云cos配置
cos:
baseUrl: https://admin-125966.cos.ap-guangzhou.myqcloud.com
secretId: AKIDdHsLgtxoSs3sWw73lz
secretKey: zZxBD0b4QcZGmdFcotm
regionName: ap-guangzhou
bucketName: admin-125966
folderPrefix: /upload
enable: false

View File

@@ -90,13 +90,5 @@ xl:
authCode:
# 登录验证码是否开启开发环境配置false方便测试
enable: false
# 腾讯云cos配置
cos:
baseUrl: https://admin-125966.cos.ap-guangzhou.myqcloud.com
secretId: AKIDdHsLgtxoSs3sWw73lz
secretKey: zZxBD0b4QcZGmdFcotm
regionName: ap-guangzhou
bucketName: admin-125966
folderPrefix: /upload

View File

@@ -0,0 +1,4 @@
aliyun.endpoint=
aliyun.accessKeyId=
aliyun.accessKeySecret=
aliyun.bucketName=