npm install qiniu-js
需要在node.js服务端上获取七牛云的token,前端请求时将token发送给前端
//七牛云配置文件
const qiniu = require('qiniu')
const express = require('express')
const app = express();
// token
var accessKey = 'jpEWLh09ox***********MXT26p3mDp23x';
var secretKey = 'fl1uGkQuB0***********8knTM9RHDF';
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
var options = {
scope: '空间名',
};
app.post('/uploadimg',(req,res) =>{
// token
var putPolicy = new qiniu.rs.PutPolicy(options);
//uploadToken就是token
var uploadToken=putPolicy.uploadToken(mac);
res.send({
status: '0',
data:uploadToken,
msg: 'sucess'
});
})
import Vue from 'vue'
import App from './App.vue'
import * as qiniu from 'qiniu-js'
// 获取七牛云token
Vue.prototype.qiniutoken = async function(){
// 获取token
var token
await axios.post('https://服务地址/uploadimg').then((res)=>{
token = res.data.data
})
return token
}
// 客户端上传图片到七牛云
Vue.prototype.uploadqiniu = async function(file,token){
var that = this
return new Promise(function(resolve){
// 配置
var params = {
file:file.imgdata,//要上传的文件
key:file.name,//自定义文件地址
token:token,
putExtra:{
fname:file.name,
params: {},
mimeType: [] || null
},
config:{
useCdnDomain:true,
region:null,
forceDirect: true, // 强制选择直传,防止大文件上传出错
}
}
// 上传图片
function next(res){
}
function error(err){
loading.close();
var returninfo = {
message:'error',
data:err
}
resolve(returninfo);
}
function complete(res){
var returninfo = {
message:'success',
data:'七牛云空间访问域名'+res.key
}
loading.close();
resolve(returninfo);
}
const observable = qiniu.upload(params.file, params.key, params.token, params.putExtra, params.config)
var subscription = observable.subscribe(next, error, complete)
})
}
在项目中写入
methods{
async upload_exe(){
var token
// 获取七牛云token
await that.qiniutoken().then(res=>{
token = res
})
// 上传原图
var datas_artwork = '选择的图片file文件'
await that.uploadqiniu(datas_artwork,token).then(res_artwork=>{
console.log('开始上传')
var upimginfo = res_artwork.data
if(res_artwork.message == 'success'){
sqlfunc.imgsrc = upimginfo
console.log('上传成功',upimginfo)
return
}else{
console.log('上传失败',res_artwork.data)
}
})
}
}