gpt4 book ai didi

angularjs - 将文件流式传输到 S3 "Error: stream ended unexpectedly"

转载 作者:搜寻专家 更新时间:2023-11-01 00:32:58 32 4
gpt4 key购买 nike

更新:

我相信这可能是由于我正在使用 express 提供的主体解析器这一事实造成的。这会扰乱多方试图解析的流吗?

我的解决方案基于 this answer .

我正在尝试做的事情:使用我的 NodeJS 服务器充当代理(出于安全目的),将文件从客户端浏览器直接流式传输到 S3。我不希望文件接触服务器的文件系统以避免瓶颈。

我收到以下错误:

events.js:72
throw er; // Unhandled 'error' event
^
Error: stream ended unexpectedly
at Form.<anonymous> (/Users/kentcdodds/Developer/bucketstreams/node_modules/multiparty/index.js:619:24)
at Form.EventEmitter.emit (events.js:117:20)
at finishMaybe (/Users/kentcdodds/Developer/bucketstreams/node_modules/multiparty/node_modules/readable-stream/lib/_stream_writable.js:443:14)
at endWritable (/Users/kentcdodds/Developer/bucketstreams/node_modules/multiparty/node_modules/readable-stream/lib/_stream_writable.js:452:3)
at Form.Writable.end (/Users/kentcdodds/Developer/bucketstreams/node_modules/multiparty/node_modules/readable-stream/lib/_stream_writable.js:419:5)
at onend (_stream_readable.js:457:10)
at process._tickCallback (node.js:415:13)

我查看了代码,但似乎不太明白导致问题的原因。我正在使用 angular-file-upload因为我在前端使用 Angular 。请求如下所示:

Request URL:http://local.bucketstreams.com:3000/upload/image
Request Headers CAUTION: Provisional headers are shown.
Accept:application/json, text/plain, */*
Cache-Control:no-cache
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryNKuH2H9IUB7kvmea
Origin:http://local.bucketstreams.com:3000
Pragma:no-cache
Referer:http://local.bucketstreams.com:3000/getting-started
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
Request Payload
------WebKitFormBoundaryNKuH2H9IUB7kvmea
Content-Disposition: form-data; name="type"

profile
------WebKitFormBoundaryNKuH2H9IUB7kvmea
Content-Disposition: form-data; name="user"

pie
------WebKitFormBoundaryNKuH2H9IUB7kvmea
Content-Disposition: form-data; name="file0"; filename="Screen Shot 2014-02-18 at 10.54.06 PM.png"
Content-Type: image/png


------WebKitFormBoundaryNKuH2H9IUB7kvmea--

下面是我的代码:

var ErrorController = require('../controller/ErrorController');
var AuthenticationController = require('../controller/AuthenticationController');
var logger = require('winston');

var http = require('http');
var util = require('util');
var multiparty = require('multiparty');
var knox = require('knox');
var Batch = require('batch');

var s3Client = knox.createClient({
secure: false,
key: process.env.S3_KEY,
secret: process.env.S3_SECRET,
bucket: process.env.S3_BUCKET_IMAGES
});

var Writable = require('readable-stream').Writable;
util.inherits(ByteCounter, Writable);
function ByteCounter(options) {
Writable.call(this, options);
this.bytes = 0;
}

ByteCounter.prototype._write = function(chunk, encoding, cb) {
this.bytes += chunk.length;
cb();
};

var supportedTypes = {
profile: true,
post: true
};

module.exports = function(app) {
app.post('/upload/image', AuthenticationController.checkAuthenticated, function(req, res) {
var type = req.body.type;
var userId = req.user._id;
if (!supportedTypes[type]) {
return ErrorController.sendErrorJson(res, 401, 'Unsupported image upload type: ' + type);
}

var headers = {
'x-amz-acl': 'public-read'
};
var form = new multiparty.Form();
var batch = new Batch();
batch.push(function(cb) {
form.on('field', function(name, value) {
if (name === 'path') {
var destPath = value;
if (destPath[0] !== '/') destPath = '/' + destPath;
cb(null, destPath);
}
});
});

batch.push(function(cb) {
form.on('part', function(part) {
if (! part.filename) return;
cb(null, part);
});
});

batch.end(function(err, results) {
if (err) throw err;
form.removeListener('close', onEnd);
var destPath = '/' + userId + results[0];
var part = results[1];

var counter = new ByteCounter();
part.pipe(counter); // need this until knox upgrades to streams2
headers['Content-Length'] = part.byteCount;
s3Client.putStream(part, destPath, headers, function(err, s3Response) {
if (err) throw err;
res.statusCode = s3Response.statusCode;
s3Response.pipe(res);
console.log('https://s3.amazonaws.com/' + process.env.S3_BUCKET_IMAGES + destPath);
});
part.on('end', function() {
console.log('part end');
console.log('size', counter.bytes);
});
});

form.on('close', function(error) {
logger.error(error);
return ErrorController.sendErrorJson(res, 500, 'There was a problem uploading the file.');
});
form.parse(req);
});
};

看起来爆炸的部分是 multiparty 并且我已经对该代码进行了一些研究但无济于事。我不确定是我发出的请求不正确还是我的服务器代码有问题。我认为这与我的 S3 存储桶没有任何关系,但我想也可能是这样。

无论如何,欢迎任何提示。

最佳答案

node-multiparty 源上有一个 S3 的例子。

https://github.com/andrewrk/node-multiparty/tree/master/examples

var http = require('http'),
util = require('util'),
multiparty = require('../'),
knox = require('knox'),
Batch = require('batch'),
PORT = process.env.PORT || 27372

var s3Client = knox.createClient({
secure: false,
key: process.env.S3_KEY,
secret: process.env.S3_SECRET,
bucket: process.env.S3_BUCKET,
});

var server = http.createServer(function(req, res) {
if (req.url === '/') {
res.writeHead(200, {
'content-type': 'text/html'
});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">' +
'<input type="text" name="path"><br>' +
'<input type="file" name="upload"><br>' +
'<input type="submit" value="Upload">' +
'</form>'
);
} else if (req.url === '/upload') {
var headers = {
'x-amz-acl': 'public-read',
};
var form = new multiparty.Form();
var batch = new Batch();
batch.push(function(cb) {
form.on('field', function(name, value) {
if (name === 'path') {
var destPath = value;
if (destPath[0] !== '/') destPath = '/' + destPath;
cb(null, destPath);
}
});
});
batch.push(function(cb) {
form.on('part', function(part) {
if (!part.filename) return;
cb(null, part);
});
});
batch.end(function(err, results) {
if (err) throw err;
form.removeListener('close', onEnd);
var destPath = results[0],
part = results[1];

headers['Content-Length'] = part.byteCount;
s3Client.putStream(part, destPath, headers, function(err, s3Response) {
if (err) throw err;
res.statusCode = s3Response.statusCode;
s3Response.pipe(res);
console.log("https://s3.amazonaws.com/" + process.env.S3_BUCKET + destPath);
});
});
form.on('close', onEnd);
form.parse(req);

} else {
res.writeHead(404, {
'content-type': 'text/plain'
});
res.end('404');
}

function onEnd() {
throw new Error("no uploaded file");
}
});
server.listen(PORT, function() {
console.info('listening on http://0.0.0.0:' + PORT + '/');
});

````

关于angularjs - 将文件流式传输到 S3 "Error: stream ended unexpectedly",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21873561/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com