Java OSS图片上传

版本:java 17(版本无关紧要)

公共参数:application文件peizhi
 

oss:
  endpoint:
  accessKeyId:
  accessKeySecret:
  roleArn:
  roleSessionName:
  bucketName:
  endpointoss:
  domain:
  bucketNamePath: 

实体类:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@Data
@ConfigurationProperties(prefix = "oss")
public class OSSProperty {
    private String endpointoss;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String domain;
    private String bucketNamePath;
}

工具类:

public String uploadFile(MultipartFile file, String pathPre) {
        String bucketName = ossProperty.getBucketName();
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = ossProperty.getEndpointoss();
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = ossProperty.getAccessKeyId();
        String accessKeySecret = ossProperty.getAccessKeySecret();
        String domain = ossProperty.getDomain();
        String bucketNamePath = ossProperty.getBucketNamePath();
        String fileName = "";
        fileName =  fileNameRound(file.getOriginalFilename());
        String url = "";
        String path = PathUtils.generateFilePath(fileName);

        if (StringUtils.isNotBlank(pathPre)) {
            if (!"/".equals(pathPre.substring(0, 1))) {
                pathPre = "/" + pathPre;
            }
            if (!"/".equals(pathPre.substring(pathPre.length() - 1, pathPre.length()))) {
                pathPre = pathPre + "/";
            }
            path = pathPre + fileName;
        }
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {

            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            path = bucketNamePath + path;
            ossClient.putObject(bucketName, path, file.getInputStream());
            url = domain + "/" + path;  //  url = "https://" + bucketName + "." + endpoint.substring(8) + "/" + path;
            return url;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "";
    }


    private String fileNameRound(String fileName){

        /**
         * 文件上传会上传特殊文件,入blob格式的图片。在这里需要将后缀拼接上
         */
        //原始文件名
        if ("blob".equals(fileName)){
            fileName = fileName + ".png";
        }
        // 这里是给文件命名,防止同个人同时上传同一个文件名的重复情况
        //截取原始文件名的后缀   dfdfdf.png
        String extension = fileName.substring(fileName.lastIndexOf("."));
        //构造新文件名称
        return com.ruoyi.common.utils.uuid.UUID.randomUUID().toString() + extension;
    }

    public static String generateFilePath(String fileName){
        //根据日期生成路径   2024/1/1/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return new  StringBuilder().append(datePath).append(uuid).append("/").append(fileName).toString();
    }

调用:

String filePathDate =  "upload/" +currentDate.getYear() + "/" + currentDate.getMonthValue() + "/" + currentDate.getDayOfMonth();
//文件的请求路径
filePath = ossPathUtils.uploadFile(file, filePathDate);
// 1、第一个参数是前端上传到后端的文件
// 2、第二个参数是上传到OSS时上传到哪个文件夹
// 我在uploadFile放里面其实已经写了文件路径的修改了,这里我在OSS创建了一个upload文件夹,我希望我上传的文件夹都在upload文件夹里面。这里后面的时间也可以不用去拼接,只上传一个自己向指定的文件夹路径也行

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值