1

My Angular 1 application saves files to S3 and allows for a wide variety of files types.

When I retrieve the objects I use the following code:

export function show(req, res) { const s3 = new aws.S3(); const s3Params = { Bucket: S3_BUCKET, Key: req.query.key + '' }; res.attachment(req.query.key + ''); var fileStream = s3.getObject(s3Params).createReadStream(); fileStream.pipe(res); } 

I would like to open the received file on the client in a new window (just like on the AWS console) but I can't figure out how to go about it.

For example on the client side does not work at all:

 .then( (data) => { var file = new Blob([data], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(file); window.open(fileURL); } ) 

I really don't understand how the concept of data streams works.

2 Answers 2

1

If you don't have to download pdf, you may open it directly from s3.

s3client.getResourceUrl("your-bucket", "some-path/some-key.jpg"); 

This will return you url to the file. So you need code like:

export function show(req, res) { this.s3client = new aws.S3({ accessKeyId: options.accessKeyId, secretAccessKey: options.secretAccessKey, region: options.region }) let resourceUrl = s3client.getResourceUrl(S3_BUCKET, req.query.key + ''); window.open(resourceUrl, '_blank'); }

I'm sorry, can't test it right now, but try. Should work.

Sign up to request clarification or add additional context in comments.

5 Comments

getResourseUrl does not appear to be in the node aws library.
I've checked - you're right, there is no such method.
http(s)://<bucket>.s3.amazonaws.com/<object> http(s)://s3.amazonaws.com/<bucket>/<object>
But you may use patterns to build urls http(s)://<bucket>.s3.amazonaws.com/<object> http(s)://s3.amazonaws.com/<bucket>/<object>
Take a look at my answer.
1

All I had to do was get a signedUrl for the resource for this to work much simpler than what I was trying to do.

export function show(req, res) { const s3 = new aws.S3(); const s3Params = { Bucket: S3_BUCKET, Key: req.query.key + '' }; s3.getSignedUrl('getObject', s3Params, (err, data) => { if (err) { console.log(err); return res.end(); } const returnData = { signedRequest: data, }; res.write(JSON.stringify(returnData)); res.end(); }); } 

and on the client all I have to do is open the link in a new tab:

openDoc(doc) { this.$http() .then( (data) => { this.$window.open(data.data.signedRequest, '_blank') } ) .catch( (err) => { this.Notification.error('failed to download attachment'); } ) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.