Java使用阿里云OSS上传图片
添加依赖
<!--阿里云存储-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<!-- 日期工具栏依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.2</version>
</dependency>
方式一
public String addAli(MultipartFile file){
String endpoint = "oss-xxxxxxxxxxxxcs.com";
String accessKeyId = "LTxxxxxxxxxxxvug";
String accessKeySecret = "L9bxxxxxxxxxxxxxxxxxLnq";
String backetName = "jxxxxxxxxxxxxmg";
String uploadUrl = null;
try {
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = file.getInputStream();
String filename = file.getOriginalFilename();
// 在文件名称中添加随机的唯一的值,防止名称一样时文件的覆盖
String uuid = UUID.randomUUID().toString().replaceAll("-","");
// 文件类型
String fileType = filename.substring(filename.lastIndexOf("."));
filename = uuid + fileType;
// 把文件安装日期进行分类,会自动创建文件夹
String datePath = new DateTime().toString("yyyy/MM/dd");
filename = datePath + "/" + filename;
ossClient.putObject(backetName, filename, inputStream);
// 关闭OSSClient
ossClient.shutdown();
// 上传文件之后的路径,自己拼接
uploadUrl = "https://"+backetName+"."+endpoint+"/"+filename;
} catch (IOException e) {
e.printStackTrace();
}
return uploadUrl;
}
方式二
public AjaxResult addAli(MultipartFile file){
String endpoint = "http://cdn.xxxxxxx.com";
String accessKeyId = "LTxxxxxxxxxxxxxxxxxxxgou";
String accessKeySecret = "gxxxxxxxxxxx3QH";
String bucketName = "mxxxxxxxxxxxxxxxxt";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String uploadUrl = null;
try {
if (file == null || file.getSize() <= 0){
return AjaxResult.error("图片不能为空");
}
// 获取上传文件的输入流
InputStream inputStream = file.getInputStream();
// 获取文件名称
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 生成上传文件名
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
String objectName = sdf.format(new Date()) + "/" + finalFileName;
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, objectName, inputStream);
// 设置URL过期时间为6小时
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 6);
// 生成以GET方法访问的签名URL,可以直接通过浏览器访问相关内容
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
// 关闭OSSClient。
ossClient.shutdown();
uploadUrl = url.toString();
System.out.println(uploadUrl);
} catch (IOException e) {
e.printStackTrace();
}
return AjaxResult.success(uploadUrl);
}
作者:山丘!
-------------------------------------------
你闻讯而来,我大喜过望,我在这等你,你又在哪呢?喜欢的话加一个“关注”呗!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!