【问题标题】:progress bar is not working file is uploading firebase进度条不起作用 文件正在上传 firebase
【发布时间】:2020-02-03 13:25:51
【问题描述】:

在这段代码中,我添加了一个文件上传框和一个进度条来显示不工作的进度

身份验证工作正常

<html>
    <head>
        <title> firebase save</title>
        <style media="screen">

        body{
            display : flex;
            min-height: 100vh;
            width : 100%;
            padding : 0;
            margin:0;
            align-items: center;
            justify-content: center;
            flex-direction: column;


                    }


            #uploader{
                -webkit-appearance: none;
                appearance: none;
                width: 50%;
                margin-bottom: 10px;

            }        
        </style>
    </head>
    <body>

<progress value="0" max = "100" id="uploader" > 0%</progress>
<input type = "file" value="upload" id="fileButton" />
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
 <script>
   // Initialize Firebase
   var config = {
  //initialization
};

   firebase.initializeApp(config);

var  uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change' , function(e) {

var file= e.target.files[0];
var storageRef = firebase.storage().ref('pics/' + file.name);
storageRef.put(file);
task.on('state_changed' , 

function progress(snapshot){
    var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    uploader.value = percentage;

},
function error(err){

},
function complete(){

}

);
});


 </script>




</body>
</html>

文件上传成功,但是进度条没有显示任何提示

控制台抛出一个名为 Uncaught ReferenceError: task is not definedat HTMLInputElement 的错误。

【问题讨论】:

    标签: javascript html firebase firebase-storage


    【解决方案1】:

    您永远不会在代码中定义什么是 task 变量,因此会出现错误。

    你应该这样做:

    var file= e.target.files[0];
    var storageRef = firebase.storage().ref('pics/' + file.name);
    
    var task = storageRef.put(file);   // <--- See the difference here
    
    task.on('state_changed' , 
    
    function progress(snapshot){
        var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        uploader.value = percentage;
    
    },
    function error(err){
    
    },
    function complete(){
    
    }
    

    文档和参考:https://firebase.google.com/docs/storage/web/upload-files#monitor_upload_progresshttps://firebase.google.com/docs/reference/js/firebase.storage.UploadTask

    【讨论】:

    • 我应该在代码中进行哪些更改以获得上传文件的下载 URL?
    • 您将在我在回答中提到的文档Section 的底部找到答案。如果我的回答对您有帮助并为您提供了最初问题的解决方案,请接受并投票(请参阅stackoverflow.com/help/someone-answers)。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 2016-03-19
    • 2018-06-30
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多