cooperation
Version:
99 lines (91 loc) • 3.66 kB
JavaScript
const http = require('http');
const path = require('path');
const fs = require('fs-extra');
const multiparty = require('multiparty');//文件上传模块
const async = require('async');//异步模块
const uuidv1 = require('uuid/v1');
const NAME = path.basename(__filename, '.js');
function upload(req, res, dir, download) {
let form = new multiparty.Form();//新建表单
//设置编辑
form.encoding = 'utf-8';
//设置文件存储路径
form.uploadDir = dir;
form.parse(req, (err, fields, files) => {
let file = files['data'][0];//获取bolb文件
let index = fields['index'][0];//当前片数
let total = fields['total'][0];//总片数
let name = fields['name'][0];//文件名称
let url = dir + '/' + name + index;//临时bolb文件新名字
let pathname = dir + '/' + name;//上传文件存放位置和名称
//修改临时文件名字
fs.rename(file.path, url, err => {
if (index === total) {//当最后一个分片上传成功,进行合并
let writeStream = fs.createWriteStream(pathname);
let aname = [];
for (let i = 1; i <= total; i++) {
aname.push(dir + '/' + name + i);
}
//async.eachLimit进行同步处理
async.eachLimit(aname, 1, (item, callback) => fs.readFile(item, (err, data) => {
if (err) throw err;
writeStream.write(data);
fs.unlink(item, () => {
});
callback();
}), err => {
if (err) {
writeStream.end();
res.writeHead(500, {'Content-Type': 'text/html;charset=utf-8'});
throw err;
}
writeStream.end();
let data = JSON.stringify({code: 0, data: download + '/' + name, msg: '上传成功'});
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
res.end(data);//返回数据
});
} else {//还没有上传文件,请继续上传
let data = JSON.stringify({code: 1, data: null, msg: '继续上传'});
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
res.end(data);//返回数据
}
});
});
}
module.exports = ({
port = 80,//端口
dir = '/',
download = "/"
} = {}) => {
fs.ensureDirSync(dir);
let server = http.createServer((req, res) => {
//cors跨域
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Content-Type', 'application/json');
//只允许post
switch (req.method) {
case 'OPTIONS':
res.end();
break;
case 'GET':
res.end(JSON.stringify({
code: 0,
msg: '获取key成功',
data: uuidv1()
}));
break;
case 'POST':
upload(req, res, dir, download);
break;
default:
res.end(JSON.stringify({
code: 500,
msg: '请用post上传',
data: []
}))
}
});
server.listen(port);
console.log(NAME + ':监听了' + port + '端口');
};