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

2020-06-17 06:43:42易采站长站整理

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 的代码为


<!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>

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

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