目錄
準(zhǔn)備工作
后端Koa
前端Vue
建議
準(zhǔn)備工作
購(gòu)買騰訊云OSS存儲(chǔ)后需要獲得以下幾個(gè)變量
SecretId:秘鑰id
SecretKey:秘鑰
Bucket:存儲(chǔ)桶名稱 可在騰訊云的圖像界面創(chuàng)建存儲(chǔ)桶
Region:購(gòu)買時(shí)選擇的區(qū)域 我這里是南京
prefix:可選 騰訊云中自定義的文件夾名稱 我這里是indexImages
const SecretId = "AK**********Od" // 秘鑰id
const SecretKey = "zi**********Am" // 秘鑰
const Bucket = "b**********9" // 存儲(chǔ)桶名稱 可在騰訊云的圖像界面創(chuàng)建
const Region = "ap-nanjing" // 購(gòu)買時(shí)選擇的區(qū)域 我這里是南京
const prefix = "indexImages/" // 可選 騰訊云中自定義的文件夾名稱 我這里是indexImages
后端項(xiàng)目中下載依賴cos-nodejs-sdk-v5
npm install cos-nodejs-sdk-v5 --save
后端Koa
/router/infoManage.router.js
路由
const Router = require("koa-router")
const { uploadImage } = require("../controller/infoManage.controller")
const infoManageRouter = new Router()
infoManageRouter.post("/indeximages/uploadImages", uploadImage)
module.exports = infoManageRouter
/controller/infoManage.controller.js
控制層
const infoManageService = require("../service/infoManage.service")
const COS = require("cos-nodejs-sdk-v5")
const { SecretId, SecretKey, Bucket, Region, prefix } = require("../app/config")
const cos = new COS({
SecretId,
SecretKey
})
class InfoManageController {
// 上傳圖像
async uploadImage(ctx) {
try {
const { base64Code, picType } = ctx.request.body // 獲取前端傳來的base64編碼和圖片后綴 如png
const dataBuffer = Buffer.from(base64Code, "base64") // base64 -> 二進(jìn)制Buffer
const data = await cos.putObject({
Bucket, // 存儲(chǔ)桶名稱
Region, // 存儲(chǔ)桶所在地域
Key: prefix + new Date().getTime() + `.${picType}`, // 可以理解為圖片存儲(chǔ)的路徑+名稱(唯一) 例如:indexImages/1670050961361.png
Body: dataBuffer, // 上傳文件的內(nèi)容,可以為 FileStream、字符串、Buffer, 我們這里接收二進(jìn)制Buffer
onProgress: function (progressData) {
console.log(progressData)
}
})
const imageUrl = `https://${data.Location}`
console.log("上傳圖片的url為", imageUrl)
await infoManageService.uploadImage(imageUrl) // 把圖片url插入到數(shù)據(jù)庫(kù)中
ctx.body = {
code: 200,
message: imageUrl
}
} catch (error) {
console.log(error)
}
}
}
module.exports = new InfoManageController()
/service/infoManage.service.js
sql
const connection = require("../app/database")
const dateFormat = require("../utils/date-handle")
class InfoManageService {
// 上傳圖片
async uploadImage(imageUrl) {
const statement = `INSERT INTO indeximages(imageUrl) VALUES(?)`
await connection.execute(statement, [imageUrl])
return true
}
}
module.exports = new InfoManageService()
前端Vue
<template>
<div id="poster-manage">
<input
@change="uploadPhoto($event)"
type="file"
accept="image/gif,image/jpeg,image/jpg,image/png"
/>
</div>
</template>
<script>
import axios from "axios"
export default {
name: 'PosterManage',
methods: {
// 上傳圖片
uploadPhoto(e) {
const filetype = file.name.split('.')[1] // 圖片類型 如png
const myImg = URL.createObjectURL(e.target.files[0])
const img = new Image()
img.src = myImg
img.onload = function () {
if (img.width !== img.height * 1.5) {
console.error('圖片的寬高比必須為1.5')
} else {
// 利用fileReader對(duì)象獲取file
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function (e) {
// 讀取到的圖片base64 數(shù)據(jù)編碼 將此編碼字符串傳給后臺(tái)即可
const imgcode = e.target.result.split('base64,')[1]
axios.post("/api/uploadImage", {imgcode, filetype}).then((res) => {
if (res.data.code === 200) {
console.log('圖片添加成功:', res.data.message)
}
})
}
}
}
}
},
}
</script>
建議
git提交的時(shí)候千萬不要把密鑰等信息提交了,不然你可能會(huì)收到如下郵件
可以創(chuàng)建一個(gè)文件.env,在這里添加相關(guān)的密鑰信息等
下載dotenv,它會(huì)幫助我們將環(huán)境變量從 .env 文件加載到中 process.env
config.js文章來源:http://www.zghlxwxcb.cn/news/detail-470578.html
const dotenv = require("dotenv")
dotenv.config()
module.exports = {
APP_HOST,
APP_PORT,
MYSQL_HOST,
MYSQL_PORT,
MYSQL_DATABASE,
MYSQL_USER,
MYSQL_PASSWORD,
SecretId,
SecretKey,
Bucket,
Region,
prefix
} = process.env
最后,記得在.gitignore里加上.env文章來源地址http://www.zghlxwxcb.cn/news/detail-470578.html
到了這里,關(guān)于【Node】騰訊云OSS存儲(chǔ)上傳圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!