koa做为中间层代理上传文件时始终出现报错,求指点,谢谢!
中间层代码
var fs = require('fs');
var os = require('os');
var path = require('path');
var parse = require('co-busboy');
var request = require('request');
var uploadFile = function*(file, params, filename, url) {
return new Promise(function(resolve, reject) {
var r = request.post(url, function (err, httpResponse, body) {
if (err) reject(err);
else resolve(body);
});
var form = r.form();
Object.keys(params).forEach(function(key) {
form.append(key, params[key]);
});
form.append('file', fs.createReadStream(file), {filename: filename});
});
};
exports.uploadFile = function*() {
var parts = parse(this), params = {};
var part, stream, url, access_token, file_name;
while (part = yield parts) {
if (part.fieldname != 'file') {
params[part[0]] = part[1];
continue;
};
stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
part.pipe(stream);
params['file_name'] = params['file_name'] || part.filename;
}
url = params.url;
file_name = params.file_name;
delete params.url;
delete params.file_name;
params.client = 'h5';
var result = yield uploadFile(stream.path, params, file_name, url);
this.sendJson(result);
}
用于测试的模拟客户端代码
var fs = require('fs');
var request = require('request');
var r = request.post('http://local.middleware.com/service/uploadFile', function optionalCallback(err, httpResponse, body) {
if (err) throw err;
console.log(body);
});
var form = r.form();
form.append('accessToken', 'dd0a81a013270eac9466f70c84640b5f');
form.append('url', 'http://localhost:3002');
form.append('file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
用户测试的模拟服务端代码
var http = require('http');
var formidable = require('formidable');
http.createServer(function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(arguments);
res.end(JSON.stringify(files));
});
}).listen(3002);
尝试从测试客户端直接提交文件到测试服务端是正常的,但是通过中间层的时候,接受客户端上传正常,但是再上传的时候出现MultipartParser.end(): stream ended unexpectedly: state = PART_DATA] 及[Error: Request aborted]错误,一直看不错中间层哪里有问题,求指点。