1、首先登錄騰訊云官網(wǎng)控制臺(tái) 進(jìn)入對象存儲(chǔ)頁面
2、找到跨越訪問CIRS設(shè)置 配置規(guī)則
?點(diǎn)擊添加規(guī)則
?填寫信息
?3、書寫代碼
這里用VUE3書寫
第一種用按鈕出發(fā)事件形式
<template>
<div>
<input type="file" @change="handleFileChange" />
</div>
</template>
<script>
import COS from "cos-nodejs-sdk-v5"; // 導(dǎo)入cos-nodejs-sdk-v5包
export default {
methods: {
handleFileChange(event) {
const file = event.target.files[0];
const cos = new COS({
SecretId: "YOUR_SECRET_ID",
SecretKey: "YOUR_SECRET_KEY",
});
// 替換成你的 Bucket 名稱和 Region
const bucket = "YOUR_BUCKET_NAME";
const region = "YOUR_BUCKET_REGION";
// 生成對象存儲(chǔ)桶中的圖片路徑
const key = `images/${file.name}`;
// 將圖片上傳到騰訊云對象存儲(chǔ)桶
cos.putObject(
{
Bucket: bucket,
Region: region,
Key: key,
Body: file,
},
(err, data) => {
if (err) {
console.error("上傳失?。?, err);
this.$message.error("上傳失敗")
} else {
console.log("上傳成功:", data.Location);
this.$message.success("上傳成功")
}
}
);
},
},
};
</script>
4、測試
點(diǎn)擊選擇文件
選擇圖片?
等待結(jié)果
?
第二種用el-upload
<el-upload v-if="imageUrl===null"
class=""
list-type="picture-card"
:show-file-list="false"
:before-upload="beforeUpload"
action=""
:on-change="handleUploadChange"
>
<el-icon class="el-icon-plus"><plus></plus></el-icon>
</el-upload>
beforeUpload(file) {
// 預(yù)覽圖片
this.file = file;
this.imageUrl = URL.createObjectURL(file);
console.log("頭像鏈接為"+this.imageUrl)
return new Promise((resolve, reject) => {
const cos = new COS({
SecretId: "", // 身份識(shí)別 ID
SecretKey: "", // 身份密鑰
});
// 替換成你的 Bucket 名稱和 Region
const bucket = "";
const region = "";
// 生成對象存儲(chǔ)桶中的圖片路徑
const key = `user_information/avatar/${this.user.username}/${file.name}`;
//待刪除的之前的圖片的key
let key1='';
console.log("key為"+key)
// 將文件轉(zhuǎn)換為 Blob 對象
const blob = new Blob([file.raw], { type: file.type });
console.log("blob"+blob)
// 將圖片上傳到騰訊云對象存儲(chǔ)桶
cos.putObject(
{
Bucket: bucket,
Region: region,
Key: key,
Body: file,
},
(err, data) => {
setTimeout(()=>{
if (err) {
console.error("上傳失?。?, err);
this.$message.error("上傳失敗");
reject(err);
} else {
// console.log("打撒筆"+this.user.avatarUrl)
console.log("上傳成功:", data.Location);
if(this.user.avatarUrl!==null){
key1 = this.user.avatarUrl.replace("https://"+bucket+".cos."+region+".myqcloud.com/", "");
// 刪除文件
console.log("key1:", key1);
cos.deleteObject({
Bucket: bucket,
Region: region,
Key: key1,
}, (err, data) => {
if (err) {
console.log('Error deleting file:', err);
} else {
console.log(data)
console.log('云端路徑為:'+key1+"的圖片已經(jīng)被刪除");
}
});
}
this.form.avatarUrl="https://"+ data.Location
this.user.avatarUrl="https://"+ data.Location
localStorage.setItem("user", JSON.stringify(this.user));
// 刷新當(dāng)前頁面
location.reload();
this.save1();
console.log(data)
// this.$message.success("上傳圖片成功");
resolve(false); // 阻止 Element-UI 的默認(rèn)上傳行為
}
},1000)
}
);
// if(key1!==''){
// }
});
},
handleUploadChange(file) {
if (file.status === "success") {
this.$message.success("上傳成功");
} else if (file.status === "error") {
this.$message.error("上傳失敗");
}
},
也可以把el-upload嵌套button包裝成這種形式
<el-upload
class=""
:show-file-list="false"
:before-upload="beforeUpload"
action=""
:on-change="handleUploadChange"
style="margin-right: 15px"
>
<el-button v-if="this.user.avatarUrl" style="background-color: #3f72af;color:
white;border-radius: 15px;width: 100px;height: 40px" type="" >更改頭像
</el-button>
</el-upload>
文章來源:http://www.zghlxwxcb.cn/news/detail-615385.html
按照這個(gè)邏輯上傳頭像的整體代碼 (寫的不好 待優(yōu)化 歡迎大神優(yōu)化)文章來源地址http://www.zghlxwxcb.cn/news/detail-615385.html
<div v-if="this.user.avatarUrl" class="avatar">
<el-image id="elimg" class="preview-image"
:src="this.user.avatarUrl"
style="width: 170px; height: 170px; position: relative; justify-content: center" >
</el-image >
</div>
<div v-else class="avatar" id="avatar">
<el-image id="elimg" v-if="imageUrl" class="preview-image"
:src="imageUrl"
:preview-src-list="[imageUrl]" style="width: 170px; height: 170px; position: relative; justify-content: center" >
</el-image >
<el-icon size="large" v-if="imageUrl" class="el-icon-close" @click="cancelUpload"><close></close></el-icon>
<el-upload v-if="imageUrl===null"
class=""
list-type="picture-card"
:show-file-list="false"
:before-upload="beforeUpload"
action=""
:on-change="handleUploadChange"
>
<el-icon class="el-icon-plus"><plus></plus></el-icon>
</el-upload>
</div>
import {Close, Plus} from "@element-plus/icons";
import COS from "cos-js-sdk-v5";
export default {
name: "UserInfo",
components: {Plus,Close},
data(){
return {
form:{},
user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")):{},
imageUrl: null,
file: null,
}
},
}
beforeUpload(file) {
// 預(yù)覽圖片
this.file = file;
this.imageUrl = URL.createObjectURL(file);
console.log("頭像鏈接為"+this.imageUrl)
return new Promise((resolve, reject) => {
const cos = new COS({
SecretId: "", // 身份識(shí)別 ID
SecretKey: "", // 身份密鑰
});
// 替換成你的 Bucket 名稱和 Region
const bucket = "";
const region = "";
// 生成對象存儲(chǔ)桶中的圖片路徑
const key = `user_information/avatar/${this.user.username}/${file.name}`;
let key1='';
console.log("key為"+key)
// 將文件轉(zhuǎn)換為 Blob 對象
const blob = new Blob([file.raw], { type: file.type });
console.log("blob"+blob)
// 將圖片上傳到騰訊云對象存儲(chǔ)桶
cos.putObject(
{
Bucket: bucket,
Region: region,
Key: key,
Body: file,
},
(err, data) => {
setTimeout(()=>{
if (err) {
console.error("上傳失?。?, err);
this.$message.error("上傳失敗");
reject(err);
} else {
// console.log("打撒筆"+this.user.avatarUrl)
console.log("上傳成功:", data.Location);
if(this.user.avatarUrl!==null){
key1 = this.user.avatarUrl.replace("https://"+bucket+".cos."+region+".myqcloud.com/", "");
// 刪除文件
console.log("key1:", key1);
cos.deleteObject({
Bucket: bucket,
Region: region,
Key: key1,
}, (err, data) => {
if (err) {
console.log('Error deleting file:', err);
} else {
console.log(data)
console.log('云端路徑為:'+key1+"的圖片已經(jīng)被刪除");
}
});
}
this.form.avatarUrl="https://"+ data.Location
this.user.avatarUrl="https://"+ data.Location
localStorage.setItem("user", JSON.stringify(this.user));
// 刷新當(dāng)前頁面
location.reload();
this.save1();
console.log(data)
// this.$message.success("上傳圖片成功");
resolve(false); // 阻止 Element-UI 的默認(rèn)上傳行為
}
},1000)
}
);
// if(key1!==''){
// }
});
},
cancelUpload() {
// 清除預(yù)覽圖片和文件
this.imageUrl = null;
this.file = null;
},
save1(){
this.request.post("/saveuser",this.form).then(res => {
if(res){
this.$message.success("保存圖片成功")
}else{
this.$message.error("保存圖片成功")
}
})
},
到了這里,關(guān)于上傳圖片到騰訊云對象存儲(chǔ)桶cos 【騰訊云對象存儲(chǔ)桶】【cos】【el-upload】【vue3】【上傳頭像】【刪除】的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!