Java 用阿里云OSS 怎样实现上传文件(源码分享)

时间:2018-11-21
本文章向大家介绍Java 用阿里云OSS 怎样实现上传文件(源码分享),需要的朋友可以参考一下

最近接到个需求,项目文件由原来上传至服务器本地改为上传至阿里oss服务器中。查看了官方相关文档后最终成功实现,在此记录一下相关经验。

官网文档:https://help.aliyun.com/document_detail/84781.html?spm=a2c4g.11186623.6.707.5a0c1bd4CT02Ig

pom文件引用:

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.3</version>
</dependency>

上传工具类:

public class AliOssUtil {

    static Logger logger = Logger.getLogger(AliOssUtil.class);

    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com"; 
    private static String accessKeyId = "<yourAccessKeyId>";
    private static String accessKeySecret = "<yourAccessKeySecret>";
    private static String bucketName = "<yourBucketName>";

    /**
     * 上传公开文件至公共读写bucket
     * @author LH_Yu
     * @Param uploadFile 上传文件
     * @Param picturePath 上传路径及取出url的key
     */
    public static String uploadOSSFree(MultipartFile uploadFile, String picturePath) throws Exception {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传:picturePath + uploadFile.getOriginalFilename() --> key
        ossClient.putObject(bucketName, picturePath + uploadFile.getOriginalFilename(), new ByteArrayInputStream(uploadFile.getBytes()));
        // 关闭client
        ossClient.shutdown();
        //设置过期时间 -- 十年
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        //取出文件上传路径
        String url = ossClient.generatePresignedUrl(bucketName, picturePath + uploadFile.getOriginalFilename(), expiration).toString();
        return url;
    }
}

关于链接有效时间:oss提供的bucket有三种类型:公共读写、公共读、私有,私有bucket下的链接会有有效时间最大为64800秒,如果只是用来存储一些无关紧要的图片等可以将bucket属性设置为公共读写。