SpringBoot + 阿里云OSS文件上传服务

分享一个关于文件上传服务的项目

pom.xml文件需要添加的依赖


            com.aliyun.oss
            aliyun-sdk-oss
            2.3.0
        

application.yml文件关于OSS的配置

ali-oss:
  endpoint: #查看你的bucketname的endpoint地址,如:http://oss-cn-shenzhen.aliyuncs.com
  bucketName: #你的bucketName
  picLocation: #你的picLocation
  accessKeyId: #你的accessKeyId
  accessKeySecret: #你的accessKeySecret

OSS配置类

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

@ConfigurationProperties(prefix="ali-oss")
@Component
public class ALiOSSConfig {
    private String endpoint;
    private String bucketName;
    private String picLocation;
    private String accessKeyId;
    private String accessKeySecret;

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getPicLocation() {
        return picLocation;
    }

    public void setPicLocation(String picLocation) {
        this.picLocation = picLocation;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }
}

OSS上传核心代码

其中,上传时putObject方法根据bucket是公有还是私有的上传方式有所区分

/*
* 实现ali oss文件上传
*/
ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

InputStream input = file.getInputStream();
ObjectMetadata meta = new ObjectMetadata();                // 创建上传Object的Metadata
meta.setContentType(type.getContentType());        // 设置上传内容类型
meta.setCacheControl("no-cache");                    // 被下载时网页的缓存行为

// 以yyyy-M-d的格式获得当前日期,用于上传文件夹区分日期
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-M-d");
FileId fileId = FileIdFactory.Generate(sourceId, type.getValue());

// filePath根据业务需求拼接                
String filePath = ossConfig.getPicLocation() + simpleDateFormat.format(new Date()) + "/" + fileId.getFileId() + type.getFileSuffix();
PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), filePath, input, meta);            //创建上传请求
ossClient.putObject(putObjectRequest);

// 私有加密url
//Date expiration = new Date(new Date().getTime() + 3600 * 1000);
//String url = ossClient.putObject(file, fileType, config.getPicLocation() + fileName + "." + fileType);

// 公有url
String url = ossConfig.getEndpoint().replaceFirst("http://", "http://" + ossConfig.getBucketName() + ".") + "/" + filePath;

 

你可能感兴趣的:(Spring,Boot)