Upload a file with $.ajax to AWS S3 with a pre-signed url

转载自:https://gist.github.com/guumaster/9f18204aca2bd6c71a24

生成预签名的Demo文档:https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/dev/PresignedUrlUploadObjectJavaSDK.html

前端写法:

生成签名:(.js)

 1 var s3 = new AWS.S3({
 2   accessKeyId: '<YOUR_ACCESS_KEY>',
 3   secretAccessKey: '<YOUR_SECRET_ACCESS_KEY>'
 4 });
 5 
 6 var uploadPreSignedUrl = s3.getSignedUrl('putObject', {
 7     Bucket: '<THE_BUCKET_NAME>',
 8     Key: '<THE_UPLOADED_FILENAME>',
 9     ACL: 'authenticated-read',
10     // This must match with your ajax contentType parameter
11     ContentType: 'binary/octet-stream'
12 
13     /* then add all the rest of your parameters to AWS puttObect here */
14 });
15 
16 var downloadPreSignedUrl = s3.getSignedUrl('getObject', {
17     Bucket: '<THE_BUCKET_NAME>',
18     Key: '<THE_UPLOADED_FILENAME>',
19     /* set a fixed type, or calculate your mime type from the file extension */
20     ResponseContentType: 'image/jpeg'
21     /* and all the rest of your parameters to AWS getObect here */
22 });
23 
24 // now you have both urls
25 console.log( uploadPreSignedUrl, downloadPreSignedUrl ); 

前端页面:(.html)

1 <form id="theForm" method="POST" enctype="multipart/form-data" >
2     <input id="theFile" name="file" type="file"/> 
3     <button id="theButton" type="submit">send 1</button>
4 </form>
5 
6 After you uploaded the file you can <a href="<YOUR_PRE_SIGNED_DOWNLOAD_URL_HERE>">download it here</a>
7 <script src="upload.js"></script>

upload:(.js)

 1 // Remember to include jQuery somewhere.
 2 
 3 $(function() {
 4 
 5   $('#theForm').on('submit', sendFile);
 6 });
 7 
 8 function sendFile(e) {
 9     e.preventDefault();
10 
11     // get the reference to the actual file in the input
12     var theFormFile = $('#theFile').get()[0].files[0];
13 
14     $.ajax({
15       type: 'PUT',
16       url: "<YOUR_PRE_SIGNED_UPLOAD_URL_HERE>",
17       // Content type must much with the parameter you signed your URL with
18       contentType: 'binary/octet-stream',
19       // this flag is important, if not set, it will try to send data as a form
20       processData: false,
21       // the actual file is sent raw
22       data: theFormFile
23     })
24     .success(function() {
25       alert('File uploaded');
26     })
27     .error(function() {
28       alert('File NOT uploaded');
29       console.log( arguments);
30     });
31 
32     return false;
33   });
34 }

 

转载于:https://www.cnblogs.com/sen-c7/p/10686495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值