本文主要是介绍nodejs + vue + element 本地调用七牛上传图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、启动 nodejs 服务
① 新建并进入一个文件夹
② 文件夹里放入server.js文件
③ 文件夹中运行终端
npm init
// 一路回车,然后
npm install qiniu
④ 运行这个js文件,启动服务
node server.js
server.js
const http = require('http');
const qiniu = require('qiniu');const accessKey = "wmRbcjYA2******************"; // 填写你的七牛云accessKey,登陆七牛云官网右上角头像上点击密钥管理即可获取
const secretKey = "mLaAIYUG*******************"; // 填写你的七牛云secretKey
const bucket = "qiniuy****"; // 你创建的七牛云存储空间名称,创建流程:对象存储->空间管理->新建空间http.createServer((req, res, next) => {const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); // 生成鉴权对象macconst options = {scope: bucket};const putPolicy = new qiniu.rs.PutPolicy(options);const uploadToken = putPolicy.uploadToken(mac);res.writeHead(200, {'Access-Control-Allow-Origin': '*' // 允许跨域访问});res.end(uploadToken);
}).listen(1234, err => { // 监听本地的1234端口号if (!err) {console.log('server listen 1234');} else {console.log(err);}
});
二、在vue项目中直接使用
<template><el-upload class="avatar-uploader" action="http://up-z2.qiniu.com/" :show-file-list="false":on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :data="postData"><img v-if="imageUrl" :src="imageUrl" class="avatar" /><el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon></el-upload>
</template><script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import type { UploadProps } from 'element-plus'import * as qiniu from 'qiniu-js'const imageUrl = ref('')
const postData = ref({token: '',key: '',
})const handleAvatarSuccess: UploadProps['onSuccess'] = (res,uploadFile
) => {// 你的专属七牛云外链地址const url = `http://s4vm5*****.clouddn.com/${ res.key }`imageUrl.value = url
}const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {postData.value.key = `${new Date().getTime()}_${file.name}`
}onMounted(() => {// 拿到后端返回的tokenaxios.get('http://localhost:1234').then(res => {console.log('token', res)postData.value.token = res.data})
})
</script><style scoped lang="scss">
.avatar-uploader .avatar {width: 178px;height: 178px;display: block;
}
</style><style>
.avatar-uploader .el-upload {border: 1px dashed var(--el-border-color);border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;transition: var(--el-transition-duration-fast);
}.avatar-uploader .el-upload:hover {border-color: var(--el-color-primary);
}.el-icon.avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 178px;height: 178px;text-align: center;
}
</style>
三、注意
① 上面的七牛云 cdn 要用 http,不能用 https ,因为我们的是测试域名,不能升级为 https ,也不能用 https 访问
② 要把私有空间改成公开空间,否则图片地址后面还应该带有 token 等参数
这篇关于nodejs + vue + element 本地调用七牛上传图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!