s3 file upload does not return response

生来就可爱ヽ(ⅴ<●) 提交于 2020-07-21 07:19:50

问题


I'm using the Node AWS-SDK to upload files to an existing S3 bucket. With the code below, the file eventually uploads but it seems to return no status code a couple of times. Also, when the file successfully uploads, the return statement does not execute.

Code

exports.create = function(req, res) {
	var stream = fs.createReadStream(req.file.path);
	var params = {
		Bucket: 'aws bucket',
		Key: req.file.filename,
		Body: stream,
		ContentLength: req.file.size,
		ContentType: 'audio/mp3'
	};
	var s3upload = s3.upload(params, options).promise();
	
	s3upload
		.then(function(data) {
			console.log(data);
			return res.sendStatus(201);
		})
		.catch(function(err) {
			return handleError(err);
		});
}

Logs

POST /api/v0/episode/upload - - ms - -
POST /api/v0/episode/upload - - ms - -
{ Location: 'https://krazykidsradio.s3-us-west-2.amazonaws.com/Parlez-vous%2BFrancais.mp3',
  Bucket: 'krazykidsradio',
  Key: 'Parlez-vous+Francais.mp3',
  ETag: '"f3ecd67cf9ce17a7792ba3adaee93638-11"' }

回答1:


Also, when the file successfully uploads, the return statement does not execute.

No value is returned from create() call, see Why is value undefined at .then() chained to Promise?

exports.create = function(req, res) {
    var stream = fs.createReadStream(req.file.path);
    var params = {
        Bucket: 'aws bucket',
        Key: req.file.filename,
        Body: stream,
        ContentLength: req.file.size,
        ContentType: 'audio/mp3'
    };
    var s3upload = s3.upload(params, options).promise();
    // return the `Promise`
    return s3upload
        .then(function(data) {
            console.log(data);
            return res.sendStatus(201);
        })
        .catch(function(err) {
            return handleError(err);
        });
}



回答2:


I figured it out. The request timeout was not long enough for the upload to finish, thus it was making the call again and so on and so on. To resolve the issue, I set the timeout for the request to 0, giving the request all the time it needs to finish the upload. With this in place, it properly returns a 201 response back to the client.

exports.create = function(req, res) {
    req.setTimeout(0); // <= set a create request to no timeout length.
    var stream = fs.createReadStream(req.file.path);
    var params = {
        Bucket: 'aws bucket',
        Key: req.file.filename,
        Body: stream,
        ContentLength: req.file.size,
        ContentType: 'audio/mp3'
    };
    var s3upload = s3.upload(params, options).promise();
    // return the `Promise`
    s3upload
        .then(function(data) {
            console.log(data);
            return res.sendStatus(201);
        })
        .catch(function(err) {
            return handleError(err);
        });
}


来源:https://stackoverflow.com/questions/45514779/s3-file-upload-does-not-return-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!