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:得在這裏插入圖片描述
在瀏覽器地址欄輸入url。
在這裏插入圖片描述
完美上傳。

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