步骤1,2,3,4都是开通阿里云oss
-
阿里云开通对象存储OSS服务
-
搞一个access-key
-
搞一个子用户
-
创建个用户, 并且给权限! 创建AccessKey同时记录下来, 关闭就没了
-
项目中引入依赖
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alicloud-oss</artifactId> </dependency>
-
在配置中配置
spring: cloud: alicloud: access-key: <用户的access-key> secret-key: <用户的secret-key> oss: endpoint: oss-cn-beijing.aliyuncs.com
-
方法中就可以用了
@Resource OSSClient sooClient; public void test() { String objectName = "文件名"; String filePath= "文件路径"; InputStream inputStream = new FileInputStream(filePath); // 创建PutObject请求。 try { InputStream inputStream = new FileInputStream(filePath); // 创建PutObject请求。 ossClient.putObject("edu-haozhancc", objectName, inputStream); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ossClient != null) { ossClient.shutdown(); } } }
就ok了