阿里云对象存储上传文件系列一
购买对象存储请查看上一篇文章。本文将详细讲解如何从后台上传文件至对象存储!
1.导入java包,我用的是maven工程,使用j2ee工程的可以自行下载jar包导入!
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.9.2</version> </dependency>2.编写连接阿里云对象代码,打开阿里云文件上传通道获取OSS对象。
public static void main(String[] args) { ClientBuilderConfiguration conf = new ClientBuilderConfiguration(); // 连接空闲超时时间,超时则关闭 conf.setIdleConnectionTime(1000); // 连接超时,默认15秒 conf.setConnectionTimeout(15 * 1000); // socket超时,默认15秒 conf.setSocketTimeout(15 * 1000); // 失败后最大重试次数 conf.setMaxErrorRetry(2); String endpoint = "***"; String accessKeyId = "*****"; String accessKeySecret = "*****"; String bucketName = "******"; OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf); }3.代码中行涉及到的秘钥和节点,需要在各自的阿里云账号获取。endpoint,在对象存储产品控制台,选择自己新建的bucket桶并点击概览查看

accessKeyId和accessKeySecret需要把鼠标放在右上角头像处,选择AccessKey 管理点击查看secret,没有的话就根据提示创建一个吧。
4.完整代码,上传我本地的一个图片到阿里云对象存储。
public static void main(String[] args) throws FileNotFoundException { ClientBuilderConfiguration conf = new ClientBuilderConfiguration(); // 连接空闲超时时间,超时则关闭 conf.setIdleConnectionTime(1000); // 连接超时,默认15秒 conf.setConnectionTimeout(15 * 1000); // socket超时,默认15秒 conf.setSocketTimeout(15 * 1000); // 失败后最大重试次数 conf.setMaxErrorRetry(2); String endpoint = "*****"; String accessKeyId = "*****"; String accessKeySecret = "*****"; String bucketName = "*****"; OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf); ObjectMetadata metadata = new ObjectMetadata(); // 本地图片路径 File file = new File("C:Users范成Desktop微信图片_20201223105506.png"); // 远程图片路径 String cloudPath = "fancheng/test/"+file.getName(); ossClient.putObject(bucketName, cloudPath, new FileInputStream(file), metadata); ossClient.shutdown(); System.out.println("文件上传完成"); }