java如何上传头像----阿里云云储存OSS

java零基础自学点击了解:https://how2j.cn

为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS。 

1、开通“对象存储OSS”服务

(1)申请阿里云账号

(2)实名认证

(3)开通“对象存储OSS”服务

 或者直接点击这个进入下面页面,点击开通:https://www.aliyun.com/product/oss

 

(4)进入管理控制台

点击最右侧创建Bucket

 填写Bucket名称

 读写权限改为:公共读

 记住下边蓝色圈出来的后边会用到

  确认即可.

 

 二:阿里云测试

依次点击进入,点击上传图像,

 拖拽或者点击选择图片,即可上传成功

 

 三:获取java代码编写必要的常量值

(1)endpoint:上边让保存记住的内容

(2)bucketName:创建Access时候的名字

(3)accessKeyId

(4)accessKeySecret

获取步骤

1.点击头像,下拉框点击accesskeys,

 2.弹出的框,点击继续使用

 创建一个AccessKey,按要求填写验证码

最后得到相应的

 四:java代码

依赖导入:

<dependencies>
    <!-- 阿里云oss依赖 -->
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
    </dependency>
    <!-- 日期工具栏依赖 -->
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
    </dependency>
</dependencies>

 配置文件:


#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev

#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=guli-file

启动类


package com.guli.oss;
@SpringBootApplication
@ComponentScan({"com.atguigu"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}

从配置文件读取常量

创建常量读取工具类:ConstantPropertiesUtil.java

使用@Value读取application.properties里的配置内容

用spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用。

public class ConstantPropertiesUtils implements InitializingBean {
    //读取配置文件内容
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketname;

    //定义公开静态常量
    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;
    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT=endpoint;
        ACCESS_KEY_ID=keyId;
        ACCESS_KEY_SECRET=keySecret;
        BUCKET_NAME=bucketname;

    }
}

2、文件上传

创建Service接口:FileService.java

 

public interface FileService {

    String upload(MultipartFile file);
}

实现:FileServiceImpl.java

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint= ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret =ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName=file.getOriginalFilename();
            //在文件名称里边添加一个随机唯一的值
            String uuid=UUID.randomUUID().toString().replaceAll("-","");
            fileName=uuid+fileName;
            //文件按日期分类存到oss
            //获取当前的日期
            String datePath=new DateTime().toString("yyyy/MMM/dd");
            fileName=datePath+"/"+fileName;

            ossClient.putObject(bucketName,fileName, inputStream);

            ossClient.shutdown();
            //返回路径
            String url="https://"+bucketName+"."+endpoint+"/"+fileName;
//            System.out.println(url);
            return url;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

3、控制层

创建controller:FileUploadController.java

@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {
    @Autowired
    private OssService ossService;
    @PostMapping
    public R uploadOssFile(MultipartFile file){
        //返回上传到oss的路径
        String url=ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    }
}

代码就写完了,可以测试了!

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章