简体   繁体   中英

How to upload file to S3 without AWS JavaScript SDK?

AWS SDK for JavaScript (even if only the S3 component is included) is a huge bulk for just some sporadic file uploads in my webapp. Is there a leaner way to upload files to an S3 bucket directly from the client's browser, given that I have the bucket name, accessKeyId and secretAccessKey at my disposal?

To upload files from browser to S3 you can use presigned PUT. This way you will not be disclosing the aws secret to the browser. You can use the minio-js library to generate presigned PUT url.

On the server side you can generate the presigned PUT url like this:

var Minio = require('minio')

// find out your s3 end point here:
// http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region

var s3Client = new Minio({
    url: 'https://<your-s3-endpoint>',
    accessKey: 'YOUR-ACCESSKEYID',
    secretKey: 'YOUR-SECRETACCESSKEY'
})
var presignedUrl = s3Client.presignedPutObject('bucket', 'object', 24*60*60)
// presignedUrl expires in 1 day

You can pass this presigned URL to the browser which can just do a simple HTTP PUT to amazon s3. The PUT request will succeed because the signature will be part of the presignedUrl.

You can also alternatively use presigned POST to upload too. Presigned POST gives much more control on the upload - like you can limit the size of the upload object, its content-type etc.

S3 supports uploads from the browser using a form post upload, with no special code needed at the browser. It involves a specific design of form and a signed policy document that allows the user to only upload files matching constraints you impose, and doesn't expose your secret key. It will optionally also redirect the browser back to your site after the upload.

http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html

尝试使用Extended S3 Browser (Chrome扩展程序)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM