文件上传---阿里云OSS

1.注册阿里云账户(注册完成后需要实名认证)

2.注册完账号之后,就可以登录阿里云

文件上传---阿里云OSS_第1张图片

3. 创建bucket

文件上传---阿里云OSS_第2张图片

4.创建 AccesskeyId

文件上传---阿里云OSS_第3张图片

文件上传---阿里云OSS_第4张图片

文件上传---阿里云OSS_第5张图片

文件上传---阿里云OSS_第6张图片

选择自己的开发语言

文件上传---阿里云OSS_第7张图片

文件上传---阿里云OSS_第8张图片

5. 阿里云Oss工具类

package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }
}

文件上传---阿里云OSS_第9张图片

将XML配置信息注入到阿里云oss对应的属性中

package com.sky.config;


import com.sky.properties.AliOssProperties;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * 配置类用于创建AliOssUtil对象
 */
@Configuration
@Slf4j
public class OssConfiguration {

    @Bean   //将当前对象交给spring容器进行管理
    @ConditionalOnMissingBean   //保证整个spring容器中只有一个aliOssUtil对象
                                //AliOssProperties 是由 @ConfigurationProperties(prefix = "sky.alioss")
                                //该注解从配置文件中读取属性自动创建的对象
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){

        log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
        return new AliOssUtil(aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName());
    }
}
package com.sky.properties;

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

@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

}
public class CommonController {

    //将阿里文件上传的工具类的对象注入进来
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result upload(MultipartFile file){
        log.info("文件上传;{}",file);

        try {
            //获取原始文件名称
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名后缀(originalFilename.lastIndexOf(".")获取最后一个点的位置开始截取
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新的文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath =aliOssUtil.upload(file.getBytes(),objectName);
            log.info("文件上传路径:{}",filePath);
            return Result.success(filePath);
        } catch (IOException e) {
            log.info("文件上传失败;{}",e);
        }
        return Result.error("err");
    }
}

你可能感兴趣的:(阿里云,云计算)