elementui 上传七牛_element ui使用上传组件上传文件到七牛(qiniu-js)
博主正在重構博客中,剛開始時靜態資源都是上傳到本地服務器的,但這個項目博主最后打算真正上線運營的。索性就改進了下,把靜態資源盡量放到云存儲中,方便后續開發。這里把方法和遇到坑給記錄下。
1.使用前提注冊七牛云并創建存儲空間
在秘鑰管理中拿到 AccessKey/SecretKey
2.工作原理
上傳文件到七牛有客戶端上傳和服務器上傳兩種方式,這里我們選擇客戶端上傳,上傳前從后端獲取token,再通過客服端直接上傳。獲得上傳成功后的key值,拼接上路徑前綴,即是文件的資源路徑,再將資源路徑存入到數據庫中。
3.后端接口搭建npm install qiniuimport Router from 'koa-router'
import axios from './utils/axios'
import qiniu from 'qiniu'
//需要填寫你的 Access Key 和 Secret Key
const accessKey = '你的 Access Key'
const secretKey = '你的 Secret Key'
//要上傳的空間
const bucket = '要上傳的空間'
//聲明路由
let router = new Router({ prefix: '/qiniu' })
//登錄接口
router.post('/upload', async (ctx, next) => {
//上傳到七牛后保存的文件名
let key = ctx.request.body.key
//生成上傳 Token
// console.log(key, bucket)
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
let putPolicy = new qiniu.rs.PutPolicy({ scope: bucket })
// 生成上傳文件的 token
let uptoken = putPolicy.uploadToken(mac)
if (uptoken) {
ctx.body = {
code: 0,
msg: '獲取上傳token成功',
uptoken
}
} else {
ctx.body = {
code: -1,
msg: '獲取token失敗'
}
}
})
export default router
更多功能可參考官方SDK文檔
4.前端頁面搭建
上傳文件組件,根據存儲區域不同設置action(具體可通過產品手冊查看),請求攜帶參數通過data綁定
class="avatar-uploader"
id="imguplad"
action="https://upload.qiniup.com"
:data="qn"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
//七牛圖片上傳
qn: {
token: '',
key: ''
}
上傳前先進行文件檢查//上傳封面前檢查
async beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isGIF = file.type === 'image/gif'
const isPNG = file.type === 'image/png'
const isBMP = file.type === 'image/bmp'
if (!isJPG && !isGIF && !isPNG && !isBMP) {
this.$message.error('上傳圖片必須是JPG/GIF/PNG/BMP 格式!')
return false
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過 2MB!')
}
//根據文件名生成上傳唯一key值
let key =
'blog/image/' +
this.utils.formatDate(new Date().getTime(), 'YY/MM/DD/hh:mm:ss/') +
file.name
console.log(key)
await this.getuploadToken(key)
return (isJPG || isGIF || isPNG || isBMP) && isLt2M
}
同時獲取token,根據日期時間設置唯一key值//獲取七牛上傳token
getuploadToken: async function(key) {
const { status, data } = await this.$axios.post('/qiniu/upload', {
key
})
// console.log(status, data)
if (status == 200 && data.uptoken) {
this.qn.token = data.uptoken
this.qn.key = key
// console.log(this.qn)
}
}
上傳成功后將返回的key值拼接為真正的url資源路徑,并設置到addpost.post_bg上,讓img標簽正常顯示圖片//返回上傳的圖片地址
handleAvatarSuccess(res, file) {
this.addpost.post_bg = 'https://gravatar.catbk.cn/' + res.key
}
效果大概這樣
文章列表
總結
以上是生活随笔為你收集整理的elementui 上传七牛_element ui使用上传组件上传文件到七牛(qiniu-js)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: archives_do.php,织梦后台
- 下一篇: w7计算机的收藏夹里弄出桌面,Win7电