1.首先安装插件 koa-multer 用于上传图片和qiniu。
npm install --save koa-multer
npm install --save koa-qiniu
2.新建文件qiniu.js
const multer = require("@koa/multer");
const Router = require("@koa/router");
const router = new Router();
var uuid = require('uuid');
const func = require("../untils/upload");
const storage = multer.diskStorage({
});
const limits = {
fields: 10,
fileSize: 500 * 1024,
files: 1,
};
const upload = multer({ storage, limits });
var fs = require('fs');
const {formatResponse} = require("../untils/common");
router.post('/upload',upload.single("file"), async (ctx, next) => {
try {
const file = ctx.file;
if (file) {
const fileName = uuid.v1();
const reader = fs.createReadStream(file.path);
const ext = file.originalname.split(".").pop();
const fileUrl = `public/${fileName}.${ext}`;
const result = await func.upToQiniu(reader, fileUrl);
console.log(result)
if (result) {
ctx.body = formatResponse("200", result, "success");
} else {
ctx.body = formatResponse("500", '上传失败', "success");
}
} else {
ctx.body = formatResponse("500", '没有选择图片', "success");
}
} catch (err) {
ctx.body = formatResponse("500", 'err', "success");
}
})
module.exports = router
3.在util文件夹中新建upload.js
var uuid = require('uuid');
var fs = require('fs');
let qiniu = require('qiniu');
const QINIU = {
accessKey: '输入Accesskey',
secretKey: '输入secretKey',
bucket: 'my-workspace-image'
}
const upToQiniu = (filePath, key) => {
const accessKey = QINIU.accessKey
const secretKey = QINIU.secretKey
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
const options = {
scope: QINIU.bucket
}
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
const config = new qiniu.conf.Config()
config.zone = qiniu.zone.zone2
const localFile = filePath
const formUploader = new qiniu.form_up.FormUploader(config)
const putExtra = new qiniu.form_up.PutExtra()
return new Promise((resolved, reject) => {
formUploader.putStream(uploadToken, key, localFile, putExtra, function (respErr, respBody, respInfo) {
if (respErr) {
reject(respErr)
} else {
resolved(respBody)
}
})
})
}
module.exports = {
upToQiniu,
}
在上传图片到七牛云时,想到不能直接放在自己的存储空间下面,所以可以在每张上传的图片路径上加上 /public
const fileUrl = `public/${fileName}.${ext}`;
这样上传的图片会是 my-workspace-image/public 里面。
4.然后再vue中,直接用element ui 控件
<el-upload
class="avatar-uploader"
name="file"
:action="'localhost:8081/qiniu/upload'"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:on-error="uploadFiled"
>
<img v-if="imageUrl" :src="imageUrl | img" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
js
handleAvatarSuccess(res, file) {
if(res.code==='200'){
this.ruleForm.courseTypeLogo = res.data.key;
this.imageUrl = res.data.key;
this.$message({
message: '上传成功',
type: 'success'
});
}else {
}
},
uploadFiled(err){
this.$message.error('上传失败');
console.log(err)
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'jpg' || 'png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG和png 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
|