一、启动 nodejs 服务
① 新建并进入一个文件夹
② 文件夹里放入server.js文件
③ 文件夹中运行终端
js
npm init
// 一路回车,然后
npm install qiniu
④ 运行这个js文件,启动服务
js
node server.js
server.js
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); // 生成鉴权对象mac
const 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项目中直接使用
html
<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(() => {
// 拿到后端返回的token
axios.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 等参数