koa2实现上传图片,并且同步上传到七牛云存储

因为升级到新的node版本,之前的通过很多上传图片的方式都已经不适用了,所以自己就写了一个对于 koa2上传图片的小demo,记录一下心得。

废话不多说,下面直接上代码,里面都有注释。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
const Koa = require('koa');
const route = require('koa-route');
const serve = require('koa-static');
const inspect = require('util').inspect
const path = require('path')
const os = require('os')
const fs = require('fs')
const Busboy = require('busboy')
const qiniu = require('qiniu')
const qiniuConfig = require('./qiniuconfig')
const app = new Koa();
app.use(serve(__dirname + '/public/'));
// 写入目录
const mkdirsSync = (dirname) => {
if (fs.existsSync(dirname)) {
return true
} else {
if (mkdirsSync(path.dirname(dirname))) {
fs.mkdirSync(dirname)
return true
}
}
return false
}
function getSuffix (fileName) {
return fileName.split('.').pop()
}
// 重命名
function Rename (fileName) {
return Math.random().toString(16).substr(2) + '.' + getSuffix(fileName)
}
// 删除文件
function removeTemImage (path) {
fs.unlink(path, (err) => {
if (err) {
throw err
}
})
}
// 上传到七牛
function upToQiniu (filePath, key) {
const accessKey = qiniuConfig.accessKey // 你的七牛的accessKey
const secretKey = qiniuConfig.secretKey // 你的七牛的secretKey
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
const options = {
scope: qiniuConfig.scope // 你的七牛存储对象
}
const putPolicy = new qiniu.rs.PutPolicy(options)
const uploadToken = putPolicy.uploadToken(mac)
const config = new qiniu.conf.Config()
// 空间对应的机房
config.zone = qiniu.zone.Zone_z2
const localFile = filePath
const formUploader = new qiniu.form_up.FormUploader(config)
const putExtra = new qiniu.form_up.PutExtra()
// 文件上传
return new Promise((resolved, reject) => {
formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr, respBody, respInfo) {
if (respErr) {
reject(respErr)
}
if (respInfo.statusCode == 200) {
resolved(respBody)
} else {
resolved(respBody)
}
})
})
}
// 上传到本地服务器
function uploadFile (ctx, options) {
const _emmiter = new Busboy({headers: ctx.req.headers})
const fileType = options.fileType
const filePath = path.join(options.path, fileType)
const confirm = mkdirsSync(filePath)
if (!confirm) {
return
}
console.log('start uploading...')
return new Promise((resolve, reject) => {
_emmiter.on('file', function (fieldname, file, filename, encoding, mimetype) {
const fileName = Rename(filename)
const saveTo = path.join(path.join(filePath, fileName))
file.pipe(fs.createWriteStream(saveTo))
file.on('end', function () {
resolve({
imgPath: `/${fileType}/${fileName}`,
imgKey: fileName
})
})
})
_emmiter.on('finish', function () {
console.log('finished...')
})
_emmiter.on('error', function (err) {
console.log('err...')
reject(err)
})
ctx.req.pipe(_emmiter)
})
}
app.use(route.post('/upload', async function(ctx, next) {
const serverPath = path.join(__dirname, './uploads/')
// 获取上存图片
const result = await uploadFile(ctx, {
fileType: 'album',
path: serverPath
})
const imgPath = path.join(serverPath, result.imgPath)
// 上传到七牛
const qiniu = await upToQiniu(imgPath, result.imgKey)
// 上存到七牛之后 删除原来的缓存图片
removeTemImage(imgPath)
ctx.body = {
imgUrl: `http://xxxxx(你的外链或者解析后七牛的路径)/${qiniu.key}`
}
}));
app.listen(3001);
console.log('listening on port 3001');

然后在同一级目录下,创建一个public文件夹,然后在下面新建一个 index.html,因为我们上面已经把这个文件夹设置为静态访问文件夹了, public/index.html 的代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input id="btn1" type="file" name="file"/>
<input id="btn2" type="submit" value="提交"/>
</body>
<script>
var btn1 = document.querySelector('#btn1')
var btn2 = document.querySelector('#btn2')
var file = null
btn1.addEventListener('change', function(e){
file = e.target.files[0]
})
btn2.onclick = function(){
var _data = new FormData();
_data.append('file', file);
xhr(_data)
}
var xhr = function(formdata){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post","http://127.0.0.1:3001/upload", true);
xmlHttp.send(formdata);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var data = xmlHttp.responseText;
console.log(data);
}
}
}
}
</script>
</html>

选择好图片,然后点击提交,就可以上传到你的七牛空间啦!

文章博客地址: http://blog.naice.me/articles

ps: 如果对你有帮助请随手丢一个 start 哦

源代码在 github: https://github.com/naihe138/koa-upload

文章目录
|