添加上传文件的进度条

时间:2019-02-06 12:30:48

标签: progress-bar axios

我有一个提交文件的表单,我的html代码在这里:

    <input type="file" name="file" id="file">
    <button onclick="upload()">upload</button>

并且我有axios代码要上传,例如此代码

  function upload() {
    var file = $('#file').prop('files')[0];
    var formdata = new FormData;
    formdata.append('file',file);
    const config = {
        onUploadProgress: function(progressEvent) {
            var percentCompleted = Math.round( (progressEvent.loaded * 100) 
             / progressEvent.total );
            console.log(percentCompleted)
        }
    };
    axios.post("/upload/test", formdata,  config,{
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

我可以在控制台中获得一定百分比的上传,但是我不知道如何在进度栏中显示此内容,您能帮我吗?

1 个答案:

答案 0 :(得分:0)

HTML5实际上具有很好的支持进度标签。例如:

<progress max="100" value="80"></progress>

因此,您所需要做的就是遵循这些原则:

onUploadProgress: function(progressEvent) {
    var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
    $('progress').attr('value', percentCompleted);
    console.log(percentCompleted)
}

浏览器支持很好: https://caniuse.com/#feat=progress