1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > nodejs+vue结合七牛云实现图片上传

nodejs+vue结合七牛云实现图片上传

时间:2020-06-11 04:39:44

相关推荐

nodejs+vue结合七牛云实现图片上传

1.这部分是前端的

主要修改七牛云的外链 以及 domain的值

//1.html代码<div class="upload"><el-uploadclass="avatar-uploader":action= domain:http-request = upqiniu:show-file-list="false":before-upload="beforeUpload"><img v-if="imageUrl" :src="imageUrl" class="avatar"><i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload></div>

//2.js代码imageUrl: '',token: {},// 七牛云的上传地址,根据本身所在地区选择,我这里是华南区domain: 'https://up-',// 这是七牛云空间的外链默认域名qiniuaddr: 'rb1db201j.hn-'upqiniu (req) {console.log(req)const config = {headers: {'Content-Type': 'multipart/form-data'}}let filetype = ''if (req.file.type === 'image/png') {filetype = 'png'} else {filetype = 'jpg'}// 重命名要上传的文件const keyname = 'lytton' + new Date() + Math.floor(Math.random() * 100) + '.' + filetype// 从后端获取上传凭证tokenaxios.get('http://127.0.0.1:3000/upload').then(res => {// console.log(res)const formdata = new FormData()formdata.append('file', req.file)formdata.append('token', res.data.upToken)formdata.append('key', keyname)// 获取到凭证以后再将文件上传到七牛云空间axios.post(this.domain, formdata, config).then(res => {this.imageUrl = 'http://' + this.qiniuaddr + '/' + res.data.keyconsole.log(this.imageUrl)})})},// 验证文件合法性beforeUpload (file) {const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'const isLt2M = file.size / 1024 / 1024 < 2if (!isJPG) {this.$message.error('上传头像图片只能是 JPG 格式!')}if (!isLt2M) {this.$message.error('上传头像图片大小不能超过 2MB!')}return isJPG && isLt2M}

//3.css代码.upload {width: 600px;margin: 0 auto;}.avatar-uploader .el-upload {border: 5px dashed #ca1717 !important;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;}.avatar-uploader .el-upload:hover {border-color: #409EFF;}.avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 178px;height: 178px;line-height: 178px;text-align: center;}.avatar {width: 178px;height: 178px;display: block;}

2.后台建一个qiniu.js

开始记得 npm 一个七牛云 具体代码不太记得了(可以手动百度一下)

let qiniu = require('qiniu'),let express = require('express');let ak = '这里是你们的ak'let sk = '你们的sk'const mac = new qiniu.auth.digest.Mac(ak, sk)const options = {scope: 'uuto', //对象存储空间名字expires: 7200}const putPolicy = new qiniu.rs.PutPolicy(options)const uploadToken = putPolicy.uploadToken(mac)module.exports = {uploadToken}

开一个接口给前端请求

const qnconfig = require('../router/qiniu.js')var express = require('express');var router = express.Router();router.get('/upload', (req, res, next) => {const token = qnconfig.uploadTokenconsole.log(token);res.send({status: 1,message: '上传凭证获取成功',upToken: token,})})module.exports = router;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。