Vue大文件分片上傳 直連AWS S3


前言

前端使用vue2+elementui2.15.6+axios0.23.0 上傳文件,直連AWS S3。進度條使用elementui2.0中的progress進度條組件。

vue中安裝的aws-sdk為2.235.1版本,即AWS SDK for JavaScript版本2,非最新的版本3

現存問題:版本3缺少認證Amazon cognito身份認證,所在寧夏區,無此服務。不清楚如何使用accessKeyId和secretAccessKey代替cognito直連s3上傳。故使用版本2。

參考鏈接:

https://aws.amazon.com/cn/blogs/china/s3-multipul-upload-practice/

https://www.cnblogs.com/lyjfight/p/12942829.html

重要::雖然我很菜,寫的也不夠好,但我不接受任何批評,本文僅供有需要的人參考及自己記錄用。

效果截圖

點擊文件上傳按鈕,選擇文件,分片上傳,進度條由0到100%,上傳過程中,按鈕禁止點擊。

代碼實現

安裝aws-sdk

npm install aws-sdk@2.235.1

需要獲取AWS的accessKeyId、secretAccessKey、region以及存儲桶名稱。存儲桶需要配置CORS(跨資源共享)

完整代碼

<template>
    <div>
        <el-button type="primary" @click="fileClick()" :loading="loading">文件上傳</el-button>
        <input type="file" id="fileExport" @change="handleFileChange" ref="inputer" style="display:none">
        <p>
            <el-progress :text-inside="true" :stroke-width="26" :percentage="progress"></el-progress>
        </p>
    </div>
</template>

<script>
    var AWS = require("aws-sdk");
    export default {
        data() {
            return {
                s3: new AWS.S3({ // AWS 認證相關
                    accessKeyId: XXX,
                    secretAccessKey: XXX,
                    region: XXX
                }),
                upload: null,
                loading: false, // 防止再次點擊
                progress: 0 ,// 進度條
                fileName: "", // 文件名稱
                suffix: "", // 文件后綴
            }
        },
        methods: {
            fileClick: function() { // 點擊button按鈕click事件
                this.$refs.inputer.dispatchEvent(new MouseEvent('click')) // 觸發input框的click事件
            },
            handleFileChange(e) { // 觸發input選擇文件事件
                var self = this;
                let inputDOM = self.$refs.inputer;
                var file = inputDOM.files[0]; // 通過DOM取文件數據
                if (file) {
                    self.loading = true;
                    self.progress = 0;
                    self.fileName = file.name;
                    self.suffix = self.fileName.split(".")[1];
                    var key = new Date().getTime() + "_" + Math.random().toFixed(2) + "." + self.suffix;
                    var params = {
                        Bucket: XXX, // 存儲桶名稱
                        Key: key, // 文件名,重名會覆蓋
                        ContentType: file.type, // 文件類型
                        Body: file, // 具體的文件
                        'Access-Control-Allow-Credentials': '*',
                        'ACL': 'public-read'
                    };
                    self.upload = self.s3.upload(params, {
                        // queueSize: 1 // 並發數
                    }).on('httpUploadProgress', function(e) { // 進度條
                        var precent = (parseInt(e.loaded, 10) / parseInt(e.total, 10)) * 100;
                        precent = parseInt(precent.toFixed(2));
                        setTimeout(function() {
                            self.progress = precent;
                            if (precent == 100) {
                                self.loading = false;
                            }
                        }, 3000);
                    });
                    self.sendUpload();
                }
            },
            sendUpload: function() { // 上傳文件
                var self = this;
                self.upload.send(function(err, data) {
                    if (err) {
                        console.log("發生錯誤:", err.code, err.message);
                        self.loading = false;
                    } else {
                        console.log("上傳成功, 返回結果");
                        console.log(data);
                        var url = data.Location; // 文件訪問地址
                    }
                })
            }
        },
    }
</script>

<style></style>

s3 存儲桶CORS

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "HEAD",
            "GET",
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "ETag",
            "x-amz-meta-custom-header"
        ]
    }
]

 


免責聲明!

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



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