底湘西网站建设,网页界面设计体会,国家信用信息公示网查询官网,网页制作教程好看视频博主正在重构博客中#xff0c;刚开始时静态资源都是上传到本地服务器的#xff0c;但这个项目博主最后打算真正上线运营的。索性就改进了下#xff0c;把静态资源尽量放到云存储中#xff0c;方便后续开发。这里把方法和遇到坑给记录下。1.使用前提注册七牛云并创建存储空…博主正在重构博客中刚开始时静态资源都是上传到本地服务器的但这个项目博主最后打算真正上线运营的。索性就改进了下把静态资源尽量放到云存储中方便后续开发。这里把方法和遇到坑给记录下。1.使用前提注册七牛云并创建存储空间在秘钥管理中拿到 AccessKey/SecretKey2.工作原理上传文件到七牛有客户端上传和服务器上传两种方式这里我们选择客户端上传上传前从后端获取token再通过客服端直接上传。获得上传成功后的key值拼接上路径前缀即是文件的资源路径再将资源路径存入到数据库中。3.后端接口搭建npm install qiniuimport Router from koa-routerimport axios from ./utils/axiosimport qiniu from qiniu//需要填写你的 Access Key 和 Secret Keyconst accessKey 你的 Access Keyconst 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 })// 生成上传文件的 tokenlet 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绑定classavatar-uploaderidimgupladactionhttps://upload.qiniup.com:dataqn:show-file-listfalse:on-successhandleAvatarSuccess:before-uploadbeforeAvatarUpload //七牛图片上传qn: {token: ,key: }上传前先进行文件检查//上传封面前检查async beforeAvatarUpload(file) {const isJPG file.type image/jpegconst isGIF file.type image/gifconst isPNG file.type image/pngconst isBMP file.type image/bmpif (!isJPG !isGIF !isPNG !isBMP) {this.$message.error(上传图片必须是JPG/GIF/PNG/BMP 格式!)return false}const isLt2M file.size / 1024 / 1024 2if (!isLt2M) {this.$message.error(上传头像图片大小不能超过 2MB!)}//根据文件名生成上传唯一key值let key blog/image/ this.utils.formatDate(new Date().getTime(), YY/MM/DD/hh:mm:ss/) file.nameconsole.log(key)await this.getuploadToken(key)return (isJPG || isGIF || isPNG || isBMP) isLt2M}同时获取token根据日期时间设置唯一key值//获取七牛上传tokengetuploadToken: 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.uptokenthis.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}效果大概这样文章列表