koa + koa-body上传文件需先设置参数:multipart=true
import koaBody from 'koa-body'
app.use(koaBody({multipart:true}))
利用可读流获取文件数据
let Writable = require('stream').Writable
class writableStream extends Writable{
constructor(){
super()
this.binaryArr = []
this.binarySize = 0
}
_write(chunk, enc,done){
this.binaryArr.push(chunk)
this.binarySize += chunk.length
done()
}
getBinary(){
return {
binaryArr: this.binaryArr,
binarySize: this.binarySize
}
}
}
fastdfs-client 下载 npm install fastdfs-client
import dfsClient from 'fastdfs-client'
class fastDFS {
constructor(){
if(fastdfs_client == null){
fastdfs_client = new dfsClient({
trackers: [
{
host: 'ip',//tracker 服务器ip
port: 22122 //tracker 端口
}
],
// 默认超时时间10s
timeout: 10000,
// 默认后缀
// 当获取不到文件后缀时使用
defaultExt: 'txt',
// charset默认utf8
charset: 'utf8'
})
}
}
//文件上传
upload(file){
// file FormData提交数据
let type = file.fields.type //文件类型
let name = file.fields.name //文件名称
let size = file.fields.size //文件大小
let files = file.files //文件
fastdfs_client.upload(files.file.path,{
method: 'upload',
group: 'group1',
size: size,
ext: type
}).then((fileId) => {
console.log('返回fileId为:',fileId)
}).catch(err => {
console.log('上传异常:',err)
})
}
//删除文件
delete(fileId){
fastdfs_client.del(fileId).then(() => {
console.log('删除成功',fileId)
}).catch(err => {
console.log('删除异常:',err)
})
}
//获取文件信息
getFileInfo(fileId){
fastdfs_client.getFileInfo(fileId).then( function(fileInfo){
console.log(fileInfo)
}).catch(err => {
console.log('查询异常:',err)
})
}
//下载文件
async download(fileId){
return await new Promise((resolve,reject) => {
let ws = new writableStream()
fastdfs_client.download(fileId, ws).then(() => {
//文件下载完成
let value = ws.getBinary() //获取文件数据
let buffer = Buffer.alloc(value.binarySize)
let index = 0
for(let i in value.binaryArr){
value.binaryArr[i].copy(buffer,index)
index += value.binaryArr[i].length
}
resolve(buffer) //返回文件数据
}).catch(err => {
console.log('下载异常',err)
resolve(err)
})
})
}
}