查看: 42|回覆: 0

javascript 上传文件到 aws s3存储桶

[複製鏈接]

4

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2010-4-30
發表於 2020-5-23 15:52:00 | 顯示全部樓層 |閲讀模式

直接上代码

<!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了



来源:https://www.cnblogs.com/lyjfight/p/12942829.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部