Spring Cloud整合Oss
阿新 • • 發佈:2020-10-12
關於建立賬號和開通Oss步驟省略
匯入依賴:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>
部分無關oss的配置省略
spring: cloud: nacos: discovery: server-addr: 192.168.162.139:8848 alicloud: access-key: XXXXXXXXXXXXXXXXXXXXXXXX secret-key: XXXXXXXXXXXXXXXXXXXXXXXX oss: endpoint: oss-cn-beijing.aliyuncs.com
測試:
import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClient; import com.aliyun.oss.OSSClientBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; @RunWith(SpringRunner.class) @SpringBootTest public class OssTest { @Autowired OSSClient ossClient; @Test public void contextLoads() throws FileNotFoundException { String bucketName = "wen-jie"; String objectName = "my1.png"; // 上傳檔案到指定的儲存空間(bucketName)並將其儲存為指定的檔名稱(objectName)。 String content = "C:\\Users\\wj\\Desktop\\snipaste_wj_20201012_194158.png"; ossClient.putObject(bucketName, objectName, new FileInputStream(content)); // 關閉OSSClient。 ossClient.shutdown(); } }