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 }

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com