在Sweetalert上显示文件的上载百分比(变量)

时间:2019-07-23 07:49:08

标签: javascript php html django ajax

我们实际上如何创建一个变量,该变量是文件在sweetalert上的上传百分比?我使用PyCharm作为平台,使用Django作为GUI框架。

我实际上已经看过几种与Ajax,PHP和sweetalert有关的问题(找不到与我的问题有关的特定问题),并尝试将其中一些解决方案混合使用,但不幸的是,没有一个他们中的人。

下面是我的当前代码:

html 中:

<form id='upload' method="post" enctype="multipart/form-data" onsubmit="myFunction()"> {% csrf_token %}

<input name="datas" type="file" id="datas"/>

<input type="submit" value="Submit" name="btnform3" style="height:6%; width:75%"/>

</form>

<script>
function myFunction() {

    Swal.fire({
        title: 'Status:',
        text: 'Files Uploading...',
        imageUrl:'static/widget-loader-lg-en.gif',
        html: '<h3 id="status"></h3>',
        showConfirmButton: false,
        allowOutsideClick: false,
    })
}

function _(el) {
    return document.getElementById(el);
}

function uploadFile() {
    var file = _("datas").files[0];
    var formdata = new FormData();
    formdata.append("datas", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.open("POST","static/upload.php");
    ajax.send(formdata);
}

function progressHandler(event) {
    var percent = (event.loaded / event.total) * 100;
    _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function completeHandler(event) {
    _("status").innerHTML = event.target.responseText;
}

upload.php 中:

<?php

$fileName = $_FILES["datas"]["name"]; // The file name
$fileTmpLoc = $_FILES["datas"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["datas"]["type"]; // The type of file it is
$fileSize = $_FILES["datas"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["datas"]["error"]; // 0 for false... and 1 for true
?>

任何评论和解决方案将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

万一有人想知道答案,那就是-删除myFunction()并添加到uploadFile()

function uploadFile() {
    var file = _("raw_mica_datas").files[0];
    var formdata = new FormData();
    formdata.append("raw_mica_datas", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.open("POST","static/upload.php");
    ajax.send(formdata);
    swal.fire({
        title: 'Status:',
        text: 'Files Uploading...',
        html: '<h3 id="status">',
        imageUrl:'static/InternetSlowdown_Day.gif',
        showConfirmButton: false,
        allowOutsideClick: false,
    })

}

干杯:)