AliYunUtils.java 1.4 KB
Newer Older
小柒2012 已提交
1 2
package com.tools.module.app.util;

3 4 5 6 7 8 9
import java.io.File;
import java.io.InputStream;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
小柒2012 已提交
10 11 12 13
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

14 15
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
小柒2012 已提交
16 17 18 19 20 21

/**
 * 阿里云存储
 */
@Component
@Configuration
22
@EnableConfigurationProperties({ AliYunProperties.class })
小柒2012 已提交
23 24
public class AliYunUtils {

25 26
    private final static Logger LOGGER = LoggerFactory.getLogger(AliYunUtils.class);

小柒2012 已提交
27 28 29
    private AliYunProperties aliYun;

    public AliYunUtils(AliYunProperties aliYun) {
30
	this.aliYun = aliYun;
小柒2012 已提交
31 32 33 34 35 36
    }

    private OSS instance;

    @PostConstruct
    public void init() {
37 38 39 40 41 42
	try {
	    instance = new OSSClientBuilder().build(aliYun.getEndpoint(), aliYun.getAccessKeyId(),
		    aliYun.getAccessKeySecret());
	} catch (Exception e) {
	    LOGGER.error("阿里云OSS初始化失败,{}。", e.getMessage());
	}
小柒2012 已提交
43 44 45 46 47
    }

    /**
     * 上传
     */
48 49
    public void upload(File file, String fileName) {
	instance.putObject(aliYun.getBucketName(), fileName, file);
小柒2012 已提交
50
    }
51

小柒2012 已提交
52 53 54
    /**
     * 上传
     */
55 56
    public void upload(InputStream file, String fileName) {
	instance.putObject(aliYun.getBucketName(), fileName, file);
小柒2012 已提交
57 58
    }
}