OSS图片上传和获取外网url

最近在项目中需要用到OSS,整理了一下具体操作步骤。
直接上代码。
1、添加依赖。
< dependency >
< groupId >com.aliyun.oss
< artifactId >aliyun-sdk-oss
< version>2.8.2< /version>

< dependency>
< groupId>com.aliyun< /groupId>
< artifactId>aliyun-java-sdk-core
< version>3.2.8

< dependency>
< groupId>com.aliyun
< artifactId>aliyun-java-sdk-dysmsapi
< version>1.1.0

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。
OSS图片上传和获取外网url_第1张图片
完美上传。

你可能感兴趣的:(学习)