所以我有一个应用程序,它允许你通过api上传文件,文件是请求,目前我正在管道写入文件系统的writeStream。
我想做的是直接管道到S3而不是文件系统。
我流式传输到文件系统的代码是:
var valid_ext = ['png', 'jpeg', 'jpg'],
max_size = 2*1024*1024,
name = req.headers['x-file-name'],
api = req.headers['x-api-key'],
size = parseInt(req.headers['content-length'], 10),
ext = path.extname(name).toLowerCase(),
filename = safeFilename(path.basename(name, ext)+ext),
timestamp = new Date().getTime(),
filepath = 'public/files/' + timestamp + '_' + filename,
imagePath = '/files/' + timestamp + '_' + filename,
writeStream = fs.createWriteStream(filepath);
if(valid_ext.indexOf(ext.substr(1)) === -1) {
res.send(JSON.stringify({error: "File does not match an accepted filetype."}));
return;
}
if(filename === ext) {
res.send(JSON.stringify({error: "Invalid file name."}));
return;
}
if(size > max_size) {
res.send(JSON.stringify({error: "File size exceeds the maximum limit."}));
return;
}
req.pipe(writeStream);
req.on('end', function(err) {
if(err) {
console.log('There was an error writing the file: ' + err);
res.send(JSON.stringify({error: "There was an error uploading the file."}));
} else {
res.send(imagePath);
}
});
哪种方法运行得很好但是我无法在任何地方找到任何关于修改它的内容而只是管道到S3,所以这就是我想出的:
var body = fs.createReadStream();
req.pipe(body);
req.on('end', function() {
s3.upload({
Bucket: 'rawnet-flytrap',
Key: project.pivotal_id + '/' + timestamp + '_' + filename, // I assume this will create a folder for me but I'm not sure :/
Body: body
}).on('httpUploadProgress', function(evt) {
console.log(evt);
}).send(function(err, data) {
console.log(err, data);
});
});
但这不起作用,任何人都可以告诉我该怎么做?就像我说的那样,我可以在网上找到任何有意义的东西。
干杯