nodekoa2实现上传图⽚并且同步上传到七⽜云存储因为升级到新的node版本,之前的通过很多上传图⽚的⽅式都已经不适⽤了,所以⾃⼰就写了⼀个对于 koa2上传图⽚的⼩demo,记录⼀下⼼得。
废话不多说,下⾯直接上代码,⾥⾯都有注释。
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 = f.Config()
// 空间对应的机房
< = 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: q.headers})
const fileType = options.fileType
const filePath = path.join(options.path, fileType)
const confirm = mkdirsSync(filePath)
if (!confirm) {
return
}
console.log('')
return new Promise((resolve, reject) => {
_('file', function (fieldname, file, filename, encoding, mimetype) {
const fileName = Rename(filename)
const saveTo = path.join(path.join(filePath, fileName))
file.ateWriteStream(saveTo))
<('end', function () {
resolve({
imgPath: `/${fileType}/${fileName}`,
imgKey: fileName
})
})
})
_('finish', function () {
console.log('')
})
_('error', function (err) {
console.log('')
reject(err)
})
})
}
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: `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')nodeselector
var btn2 = document.querySelector('#btn2')
var file = null
btn1.addEventListener('change', function(e){
file = e.target.files[0]
})
var _data = new FormData();
_data.append('file', file);
xhr(_data)
}
var xhr = function(formdata){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post","127.0.0.1:3001/upload", true);
xmlHttp.send(formdata);
adyState==4){
if(xmlHttp.status==200){
var data = sponseText;
console.log(data);
}
}
}
}
</script>
</html>
选择好图⽚,然后点击提交,就可以上传到你的七⽜空间啦!
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论