java使用阿里云oss上传文件测试案例+上传策略包装类

产品文档地址:
https://help.aliyun.com/product/31815.html
产品购买地址:
https://www.aliyun.com/search?scene=all&k=oss
在官网首先购买产品,开通oss服务后进入控制台:
在这里插入图片描述
在https://developer.aliyun.com/ask/2061
查看相关的endpoint地址(找到自己所在的区域)

在控制台
https://oss.console.aliyun.com/overview
查找accesskey入口:
在这里插入图片描述
获得自己的accessKeyId和accessKeySecret
在控制台点击新建bucket,自己定义名字

进入自己项目导入依赖:

   <dependency>
        <groupId >com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>2.8.2</version>
        </dependency>
        <dependency>
        <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.1.0</version>
        </dependency>

新建一个单元测试:

    private String endpoint ="https://oss-cn-beijing.aliyuncs.com";//(写自己endpoint对应的地址)
    private String accessKeyId="...";
    private String secretAccessKey="...";
    private String bucketName="...";
    @Test
    public void uploadByOss() throws FileNotFoundException {
    
    
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId, secretAccessKey);
        InputStream inputStream = new FileInputStream("C:\\Users\\14172\\Pictures\\0.png");
//上传图片,第一个参数为bucketName,第二个参数key为上传的文件路径名称,第三个为InputStream
        ossClient.putObject(bucketName ,"upload/" +"aa.jpg", inputStream);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL,第一个参数为bucketName,第二个参数key为上传的文件路径名称,第三个为过期时间
        URL url = ossClient.generatePresignedUrl(bucketName ,"upload/"+"aa.jpg" , expiration);
        System.out.println(url);

    }

点击运行后可以看到文件管理中多了一个文件夹,下面有自己上传的文件:
在这里插入图片描述
在程序运行后得到的url点击后会跳转到网页自动下载:
在这里插入图片描述
在这里插入图片描述
点击后可以看到自己刚刚上传的文件

也可以用一个类将oss上传包装起来:

@Service
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl {
    
    
    @Autowired
    private OssConfigProperties ossConfigProperties;

    @Override
    public Boolean exists(String filePath) {
    
    
        return getOssClient().doesObjectExist(ossConfigProperties.getBucketName(), filePath);
    }

    @Override
    public void upload(String path, String fileName, InputStream inputStream) {
    
    
        getOssClient().putObject(ossConfigProperties.getBucketName(), path + fileName, inputStream);
    }

    @Override
    public String getFileAccessUrl(String filePath) {
    
    
        return ossConfigProperties.getUrl() + filePath;
    }

    /**
     * 获取ossClient
     *
     * @return {@link OSS} ossClient
     */
    private OSS getOssClient() {
    
    
        return new OSSClientBuilder().build(ossConfigProperties.getEndpoint(), ossConfigProperties.getAccessKeyId(), ossConfigProperties.getAccessKeySecret());
    }

}

在yml文件中写oss配置:

upload:
  mode: oss
  oss:
    url: https://OSS域名/
    endpoint: oss-cn-beijing-.aliyuncs.com
    accessKeyId: ..
    accessKeySecret: ..
    bucketName: ..

获得配置文件的值:

@Data
@Configuration
@ConfigurationProperties(prefix = "upload.oss")
public class OssConfigProperties {
    
    

    /**
     * oss域名
     */
    private String url;
    private String endpoint;

    /**
     * 访问密钥id
     */
    private String accessKeyId;

    /**
     * 访问密钥密码
     */
    private String accessKeySecret;
    private String bucketName;

}

上传策略抽象类:

@Service
public abstract class AbstractUploadStrategyImpl {
    
    

    @Override
    public String uploadFile(MultipartFile file, String path) {
    
    
        try {
    
    
            // 获取文件md5值
            String md5 = FileUtils.getMd5(file.getInputStream());
            // 获取文件扩展名
            String extName = FileUtils.getExtName(file.getOriginalFilename());
            // 重新生成文件名
            String fileName = md5 + extName;
            // 判断文件是否已经上传
            if (!exists(path + fileName)) {
    
    
                upload(path, fileName, file.getInputStream());
            }
            return getFileAccessUrl(path + fileName);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            throw new BizException("文件上传失败");
        }
    }
      public abstract Boolean exists(String filePath);
}

猜你喜欢

转载自blog.csdn.net/qq_41358574/article/details/120796503