天天看點

OSS圖檔上傳和擷取外網url

最近在項目中需要用到OSS,整理了一下具體操作步驟。

直接上代碼。

1、添加依賴。

< dependency >

< groupId >com.aliyun.oss</ groupId >

< artifactId >aliyun-sdk-oss</ artifactId>

< version>2.8.2< /version>

</ dependency>

< dependency>

< groupId>com.aliyun< /groupId>

< artifactId>aliyun-java-sdk-core</ artifactId>

< version>3.2.8</ version>

</ dependency>

< dependency>

< groupId>com.aliyun</ groupId>

< artifactId>aliyun-java-sdk-dysmsapi</ artifactId>

< version>1.1.0</ version>

</ dependency>

2、測試類代碼

import com.aliyun.oss.OSSClient;

import java.io.FileInputStream;

import java.io.InputStream;

import java.net.URL;

import java.util.Date;

public class Demo {

private String endpoint =“";

private String accessKeyId="”;

private String secretAccessKey="**********";

private String bucketName="*****";

public static void main(String[] args) throws FileNotFoundException{

//建立OSSClient對象,三個參數endpoint,accessKeyId,secretAccessKey需要在阿裡雲背景去申請。

OSSClient ossClient = new OSSClient(endpoint,accessKeyId, secretAccessKey);

InputStream inputStream = new FileInputStream(“E://aa.jpg”);

//上傳圖檔,第一個參數為bucketName,第二個參數key為上傳的檔案路徑名稱,第三個為InputStream

ossClient.putObject(bucketName ,“upload/” +“aa.jpg”, inputStream);

Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);

// 生成URL,第一個參數為bucketName,第二個參數key為上傳的檔案路徑名稱,第三個為過期時間

URL url = ossClient.generatePresignedUrl(bucketName ,“upload/”+“aa.jpg” , expiration);

System.out.println(url);

}

}

啟動執行得到url:

OSS圖檔上傳和擷取外網url

在浏覽器位址欄輸入url。

OSS圖檔上傳和擷取外網url

完美上傳。

繼續閱讀