虽然平常学习用的不多,但是用的时候再去找官方文档,也很繁琐,不如直接整理以下,方便粘贴复制,本文介绍两种图片上传方式①普通上传②服务端签名直传
加载maven依赖?
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
?如果使用的是Java 9及以上的版本,则需要添加JAXB相关依赖
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
?需要先从阿里云获取相关accessKeyId和accessKeySecret,并创建bucket,找到创建好的就可以找到相关访问路径和endpoint?
?
附上传代码?
@Test
public void testFindPath() throws FileNotFoundException {
String endpoint = "oss-cn-beijing.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = "你的accessKeyId ";
String accessKeySecret = "你的accessKeySecret ";
String bucketName = "你的bucketName ";
// 创建OSSClient实例。
/*OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);*/
InputStream inputStream = new FileInputStream("C:\\Users\\c2405\\Desktop\\R-C.jpg");
ossClient.putObject(bucketName, "java.png", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传成功");
}
? ? ? 服务端签名直传是指在服务端生成签名,将签名返回给客户端,然后客户端使用签名上传文件到OSS。由于服务端签名直传无需将访问密钥暴露在前端页面,相比客户端签名直传具有更高的安全性。本文介绍如何进行服务端签名直传。?
?
如果使用微服务可以直接加载一个maven依赖?,这样我们可以直接在当前类中注入OSS 对象使用
<!-- aliyun:对象存储oss -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alicloud-oss</artifactId>
</dependency>
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.lei.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author: 青山猿
* @date: Created in 2023/12/26 0:20
* @description:
*/
@RestController
public class OssController {
@Autowired
OSS ossClient;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endpoint;
@Value("${spring.cloud.alicloud.oss.bucket}")
private String bucket;
@RequestMapping("/oss/policy")
public R policy(){
// 填写Host名称,格式为https://bucketname.endpoint。
//例如: https://guli-mall-admin.oss-cn-beijing.aliyuncs.com/123.jpg
String host = "https://"+bucket+"."+endpoint;
// 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
//String callbackUrl = "https://192.168.0.0:8888";
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = format+"/";
Map<String, String> respMap = null;
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
// PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
respMap = new LinkedHashMap<String, String>();
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return R.ok().put("data",respMap);
}
}
?最后可以搭配element-ui上传组件使用
?
<el-upload
class="upload-demo"
action="objData.host"
:before-upload="ossPolicy"
:file-list="fileList"
:data='objData'
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<script>
export default {
data() {
return {
fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
objData:{
OSSAccessKeyId:'',
policy:'',
Signature:'',
dir:'',
host:'',
key:''
}
};
},
methods: {
ossPolicy(file){
//在上传前,先进行服务器签名
return new Promise((resolve,reject)=>{
this.axios.get('http://loclhost:8080/oss/policy').then(res=>{
//根据后台响应结果对objData赋值
this.objData.OSSAccessKeyId=res.data.accsessid;
this.objData.policy=res.data.policy;
this.objData.Signature=res.data.signature;
this.objData.dir=res.data.dir;
this.objData.host=res.data.host;
this.objData.key=res.data.dir+"${filename}";
resolve(true); //继续上传
}).catch(error=> {
console.log(error);
reject(false); //停止上传
})
})
}
}
}
</script>
注意: 图片上传完要将路径保存在数据库中然后查询赋值给fileList这个数组,刷新页面就不会消失了(要注意fileList格式)
最后不要忘了在给自己的?accessKeyId添加相应权限,然后在阿里云上配置oos跨域,想要图片避免覆盖可以加入UUID等唯一标识