在上代码之前,首先需要注册七牛云账号,开通七牛云对象存储服务。官方会提供 accessKey 和 secretKey 作为授权token的发放;其次还需要在后台管理新建存储空间。
使用express实现文件上传
安装
npm install formidable qiniu --save-dev
首先创建 config.js 文件用来通用参数的配置
let config = {};
config.accessKey = "xxx";
config.secretKey = 'xxx';
config.bucket = 'xxx'; //存储空间的名字
config.url = 'xxx'; //配置的域名
module.exports = config;
创建 qn.js 文件封装七牛上传及验证API
let qiniu = require('qiniu');
let formidable = require('formidable');
let fs = require('fs');
let config = require('./config');
let qn = {};
// 要上传的空间及参数
let bucket = config.bucket;
let accessKey = config.accessKey
let secretKey = config.secretKey
// 获取七牛云token
qn.uptoken = function (bucket) {
var putPolicy = new qiniu.rs.PutPolicy({ scope: bucket });
var accessKey = accessKey;
var secretKey = secretKey;
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
var uploadToken = putPolicy.uploadToken(mac);
return uploadToken;
}
// 文件上传配置及构建
qn.upFlie = function (req, callback) {
let callbackObj = {}; //回调函数返回的对象
var form = new formidable.IncomingForm(); //创建上传表单
form.encoding = 'utf-8'; //设置编辑
form.keepExtensions = true; //保留后缀
form.parse(req, function (err, fields, files) {
if (err) {
callbackObj.status = 1;
callbackObj.msg = err;
console.log('err==', err);
return callback(callbackObj);
}
//上传到七牛后保存的文件名
let key = new Date().getTime();
//生成上传 Token
let token = qn.uptoken(bucket);
//要上传文件的本地路径
let filePath = files.file.path;
//如果是表单的数据提交会存储在fields中,图片文件提交会存储在files中 files.file中的file指的是前端设定input的name一般设置为file
// 构造上传函数
// 文件上传(四行代码都是七牛云上传文件的配置设置)
var Config = new qiniu.conf.Config();
Config.zone = qiniu.zone.Zone_z1;
var formUploader = new qiniu.form_up.FormUploader(Config);
var putExtra = new qiniu.form_up.PutExtra();
formUploader.putFile(token, key, filePath, putExtra, function (respErr, respBody, respInfo) {
if (respErr) {
callbackObj.status = 1;
callbackObj.msg = respErr;
return callback(callbackObj);
}
if (respInfo.statusCode === 200) { // 上传成功
// 输出 JSON 格式
var response = {
"url": `${config.url}/${respBody.key}`
};
callbackObj.status = 0;
callbackObj.data = response;
return callback(callbackObj);
} else { // 上传失败
callbackObj.status = 1;
callbackObj.msg = respBody;
return callback(callbackObj);
}
})
})
}
module.exports = qn;
在 index.js 使用封装好的 qn API
const express = require("express")
let qn = require('./qn');
const app = express()
app.use((req, res, next) => {
//设置请求头
res.set({
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
'Content-Type': 'application/json; charset=utf-8'
})
req.method === 'OPTIONS' ? res.status(204).end() : next()
})
let result = function (obj,bool){
if(bool){
return {status:0,data:obj};
}else{
return {status:1,data:obj};
}
}
app.post("/upFlie",function(req,routerRes){
try{
qn.upFlie(req,function(res){
console.log("res",res)
if(res.status == 0){
routerRes.json(result(res.data,true));
}else{
routerRes.json(result(res.msg,false));
}
})
}catch(err){
if(err){
console.log("trychtch报错====",err)
}
}
})
app.get("/viodeInfo",function(req,res){
let response = qn.parseCode(req.query.code)
res.send(JSON.stringify({
data:{
url:response
},
message:"查询成功"
}))
})
app.listen(7501,(err)=>{
if(err){
console.log("服务器启动失败")
}else{
console.log("服务器启动成功")
}
})
注意在获取视频地址时,由于使用了私用存储空间,七牛云对地址加入了token授权的时常,因此需要对地址进行私有地址解析,在 qn.js 添加解析API
// 解密私有空间
qn.parseCode = function (keyCode) {
// 配置私有空间参数
let key = keyCode
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
var Config = new qiniu.conf.Config();
Config.zone = qiniu.zone.Zone_z1;
var bucketManager = new qiniu.rs.BucketManager(mac, Config);
var privateBucketDomain = config.url;
var deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
var privateDownloadUrl = bucketManager.privateDownloadUrl(privateBucketDomain, key, deadline);
return privateDownloadUrl
}
前端调用-使用elementUI 上传组件
<el-upload
class="upload-demo"
:on-success="success"
:on-error="error"
action="http://localhost:7501/upFlie">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>