javascript 上傳文件到 aws s3存儲桶


直接上代碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- <script src="https://sdk.amazonaws.com/js/aws-sdk-2.410.0.min.js"></script> -->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.235.1.min.js"></script>
</head>

<body>
   <input id="file-chooser" type="file"/>
    <button id="upload-button">Upload</button>
    <p id="results"><p></p>
    <script type="text/javascript">
    /// <reference types="aws-sdk" />
    var credentials = {
        accessKeyId: 'xxxxxxxxxxxxx',
        secretAccessKey: 'xxxxxxxxxxxxxx'
    }; //秘鑰形式的登錄上傳
    AWS.config.update(credentials);
    AWS.config.region = 'xxxxxxxxxxxx'; //設置區域

    // create bucket instance
    var bucket = new AWS.S3({ params: { Bucket: 'xxxxxxxxx' } }); //選擇桶
    var fileChooser = document.getElementById('file-chooser');
    var button = document.getElementById('upload-button');
    var results = document.getElementById('results');
    button.addEventListener('click', function() {
        var file = fileChooser.files[0];
        if (file) {
            results.innerHTML = '';
            var params = { Key: file.name, ContentType: file.type, Body: file, 'Access-Control-Allow-Credentials': '*', 'ACL': 'public-read' }; //key可以設置為桶的相抵路徑,Body為文件, ACL最好要設置
            console.log(params)
            bucket.upload(params, function(err, data) {
                console.log(err); //打印出錯誤
                results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
            });
        } else {
            results.innerHTML = 'Nothing to upload.';
        }
    }, false);
    </script>
</body>

</html>

2.需要在aws s3中的cors進行配置如下圖

 附代碼

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <ExposeHeader>ETag</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

 

如果出現 TypeError: m.upload.addEventListener is not a function

查看是否在文件中引入mock把它去掉就ok了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM