前提準(zhǔn)備好阿里云對(duì)象存儲(chǔ)的賬號(hào)->創(chuàng)建一個(gè)bucket(設(shè)置好訪問(wèn)權(quán)限)->創(chuàng)建用于上傳文件的子賬號(hào)得到accessKey和secretKey以及endpoint->sdk例子java簡(jiǎn)單上傳的例子測(cè)試
引入alicloud-oss對(duì)象純存儲(chǔ)相關(guān)的依賴(lài)
在application.yml中配置accessKey和secretKey即可
使用OssClient對(duì)象調(diào)用方法上傳即可
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.FileInputStream;
import java.io.InputStream;
public class Demo {
public static void main(String[] args) throws Exception {
? ? ? ? //accessKey和secretKey以及endpoint在配置文件中指定的話這里就不用重復(fù)指定
// Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫(xiě)。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云賬號(hào)AccessKey擁有所有API的訪問(wèn)權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM用戶進(jìn)行API訪問(wèn)或日常運(yùn)維,請(qǐng)登錄RAM控制臺(tái)創(chuàng)建RAM用戶。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填寫(xiě)B(tài)ucket名稱(chēng),例如examplebucket。
String bucketName = "examplebucket";
// 填寫(xiě)Object完整路徑,完整路徑中不能包含Bucket名稱(chēng),例如exampledir/exampleobject.txt。
String objectName = "exampledir/exampleobject.txt";
// 填寫(xiě)本地文件的完整路徑,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路徑,則默認(rèn)從示例程序所屬項(xiàng)目對(duì)應(yīng)本地路徑中上傳文件流。
String filePath= "D:\\localpath\\examplefile.txt";
// 創(chuàng)建OSSClient實(shí)例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 創(chuàng)建PutObjectRequest對(duì)象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 設(shè)置該屬性可以返回response。如果不設(shè)置,則返回的response為空。
putObjectRequest.setProcess("true");
// 創(chuàng)建PutObject請(qǐng)求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
// 如果上傳成功,則返回200。
System.out.println(result.getResponse().getStatusCode());
} 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());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
一,項(xiàng)目結(jié)合實(shí)例
先發(fā)送請(qǐng)求獲得policy 在將對(duì)象發(fā)送阿里云對(duì)象存儲(chǔ)服務(wù)器 減輕后端壓力
建立一個(gè)oss服務(wù)器
將oss相關(guān)配置寫(xiě)在配置文件中
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
application:
name: gulimall-third-party
alicloud:
access-key: LTAI5t6G5JAZ9RB*********** # 修改為自己的
secret-key: QhhibxJFoXR9qUs*********** # 修改為自己的
oss:
endpoint: oss-cn-************* # 修改為自己的
bucket: test # 修改為自己的
server:
port: 30000
編寫(xiě)controller前端請(qǐng)求這個(gè)controller獲得policy
package com.wcw.gulimall.third.party.controller;
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.wcw.gulimall.third.party.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;
/**
* @ClassName com.wcw.gulimall.third.party.controller.OssController
* @Description:
* @Author wcw
* @Version V1.0 Created on :2023/3/2 17:25
*/
@RestController
public class OssController {
@Autowired
private OSS ossClient;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endPoint;
@Value("${spring.cloud.alicloud.oss.bucket}")
private String bucket;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@RequestMapping("/oss/policy")
public R policy() {
// 填寫(xiě)Host地址,格式為https://bucketname.endpoint。
String host = "https://" + bucket + "." + endPoint;
// 設(shè)置上傳回調(diào)URL,即回調(diào)服務(wù)器地址,用于處理應(yīng)用服務(wù)器與OSS之間的通信。OSS會(huì)在文件上傳完成后,把文件上傳信息通過(guò)此回調(diào)URL發(fā)送給應(yīng)用服務(wù)器。
// String callbackUrl = "https://192.168.0.0:8888";
// 設(shè)置上傳到OSS文件的前綴,可置空此項(xiàng)。置空后,文件將上傳至Bucket的根目錄下。
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = format+"/";
Map<String, String> respMap = new LinkedHashMap<String, String>();
// 創(chuàng)建ossClient實(shí)例。
// OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
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.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);
}
}
返回下面的對(duì)象文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-755725.html
{?policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: '',}
攜帶policy按照aliyun oss官方文檔發(fā)送即可文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-755725.html
<template>
<div>
<el-upload
action="http://gulimall-wcw.oss-cn-chengdu.aliyuncs.com"
:data="dataObj"
list-type="picture"
:multiple="false" :show-file-list="showFileList"
:file-list="fileList"
:before-upload="beforeUpload"
:on-remove="handleRemove"
:on-success="handleUploadSuccess"
:on-preview="handlePreview">
<el-button size="small" type="primary">點(diǎn)擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過(guò)10MB</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="fileList[0].url" alt="">
</el-dialog>
</div>
</template>
<script>
import {policy} from './policy'
import { getUUID } from '@/utils'
export default {
name: 'singleUpload',
props: {
value: String
},
computed: {
imageUrl() {
return this.value;
},
imageName() {
if (this.value != null && this.value !== '') {
return this.value.substr(this.value.lastIndexOf("/") + 1);
} else {
return null;
}
},
fileList() {
return [{
name: this.imageName,
url: this.imageUrl
}]
},
showFileList: {
get: function () {
return this.value !== null && this.value !== ''&& this.value!==undefined;
},
set: function (newValue) {
}
}
},
data() {
return {
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: '',
// callback:'',
},
dialogVisible: false
};
},
methods: {
emitInput(val) {
this.$emit('input', val)
},
handleRemove(file, fileList) {
this.emitInput('');
},
handlePreview(file) {
this.dialogVisible = true;
},
beforeUpload(file) {
let _self = this;
return new Promise((resolve, reject) => {
policy().then(response => {
console.log("response:",response);
_self.dataObj.policy = response.data.policy;
_self.dataObj.signature = response.data.signature;
_self.dataObj.ossaccessKeyId = response.data.accessId;
_self.dataObj.key = response.data.dir +getUUID()+'_${filename}';
_self.dataObj.dir = response.data.dir;
_self.dataObj.host = response.data.host;
console.log("_self.dataObj:",_self.dataObj);
resolve(true)
}).catch(err => {
reject(false)
})
})
},
handleUploadSuccess(res, file) {
console.log("上傳成功...")
this.showFileList = true;
this.fileList.pop();
this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) });
this.emitInput(this.fileList[0].url);
}
}
}
</script>
<style>
</style>
到了這里,關(guān)于OSS對(duì)象存儲(chǔ)的簡(jiǎn)單實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!