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);
    }
}

代碼就寫完了,可以測試了!

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