aliyun-oss

oss 存储

  • yml
file:
  local:
    path: localFile
    prefix: statics
    urlPrefix: http://api.gateway.com:8080/api-f${file.local.prefix}
  aliyun:
    endpoint: http://oss-cn-beijing.aliyuncs.com
    accessKeyId: xxx
    accessKeySecret: xxx
    bucketName: sam-bucker
    saveUrl: https://sam-bucker.oss-cn-beijing.aliyuncs.com
    subUploadDirReplacement: current_date
    uploadDir: audit/${file.aliyun.subUploadDirReplacement}/
  • 依赖
		<dependency>
			<groupId>com.aliyun.oss</groupId>
			<artifactId>aliyun-sdk-oss</artifactId>
			<version>2.8.2</version>
		</dependency>
  • 工具类
@Data
@Configuration
@ConfigurationProperties(prefix = "file.aliyun")
public class AliyunConfig {

	private String accessKeyId;

	private String accessKeySecret;

	private String endpoint;

	private String bucketName;

	private String saveUrl;

	private String uploadDir;

	private String subUploadDirReplacement;

	/**
	 * 阿里云文件存储client
	 * 
	 */
	@Bean
	public OSSClient ossClient() {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		return ossClient;
	}

}




@Slf4j
@Configuration
public class FileUploadUtil {
    public static final String ERROR_MSG = "上传失败";

    @Autowired
    private AliyunConfig properties;

    @Autowired
    private OSSClient ossClient;
    /**
     * 文件上传,返回新文件上传后的文件路径
     *
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
        String bucketName = properties.getBucketName();
        if (!ossClient.doesBucketExist(bucketName)) {
            log.error("您的Bucket不存在,创建Bucket:" + bucketName + "。");
            ossClient.createBucket(bucketName);
        }
        try {
            long beginTime = System.currentTimeMillis();
            log.info("上传文件到oss begin, currentTime: {}", beginTime);
            String fileName = file.getOriginalFilename();
            // 按日期分目录存储
            long currentTime = System.currentTimeMillis();
            String fileKey = properties.getUploadDir().replace(properties.getSubUploadDirReplacement(), DateFormatUtils.format(currentTime, "yyyy-MM-dd")) + currentTime + fileName;
            // 上传到阿里云
            // 桶 名称  文件流
            ossClient.putObject(bucketName, fileKey, file.getInputStream());
            log.info("{}存入OSS成功,共消耗{}秒", fileKey, (System.currentTimeMillis() - beginTime) / 1000d);
            // 生成URL
            return fileKey;
        } catch (IOException e) {
            log.error(ERROR_MSG, e.getMessage());
            return ERROR_MSG;
        } finally {
            // 关闭OSSClient
           // ossClient.shutdown();
        }
    }

    /** 
     *删除
     */
    public boolean deleteFile(String path) {
        // path : 桶目录之后路径
        try {
            ossClient.deleteObject(properties.getBucketName(), path);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } 
        return true;
    }

}

你可能感兴趣的:(java,java)