jQuery实现上传文件获取进度条

时间:2022-07-24
本文章向大家介绍jQuery实现上传文件获取进度条,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>上传文件</title>
</head>

<body>
   <input type="file" id="upload" />
  <!-- accept="image/*" -->
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
    $("#upload").change(function (link) {
        var file = link.target.files[0];
        var formData = new FormData();
        formData.append("file", file);
        formData.append("key", "Gn15XGagWO");
        $.ajax({
            url: "upload",
            type: "post",
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
			xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                if (onprogress && xhr.upload) {
                    xhr.upload.addEventListener("progress", onprogress, false);
                    return xhr;
                }
            },
            success: function (res) {
            }
        })
    })
  function onprogress(evt) {
        console.log(evt)
        var loaded = evt.loaded;     //已经上传大小情况 
        var tot = evt.total;      //附件总大小 
        var per = Math.floor(100 * loaded / tot);  //已经上传的百分比 
        console.log(loaded)
        console.log(tot)
        console.log(per)
  }
</script>

</html>

ajax请求记得要加这两句

contentType: false, processData: false,