显示多文件上传 Jquery/Ajax 的进度

     2023-03-22     184

关键词:

【中文标题】显示多文件上传 Jquery/Ajax 的进度【英文标题】:Show a progress on multiple file upload Jquery/Ajax 【发布时间】:2014-06-06 19:04:36 【问题描述】:

我有允许用户上传多个文件的上传表单。我决定如果文件很大,进度条会很好。下面是我的源代码。我是 jquery 的新手,通常我只会使用 php,但我发现 ajax 对用户更友好。

<div id="new_upload">
    <div class="close_btn"></div>
    <div id="uploads"></div>
    <form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file">
    <fieldset><legend>Upload an image or video</legend>
    <input type="file" id="file" name="file[]" placeholder="Upload Image or Video" multiple /><input type="submit" value="upload file" id="upload_file_btn" required />
    </fieldset>

    <div class="bar">
        <div class="bar_fill" id="pb">
            <div class="bar_fill_text" id="pt"></div>
        </div>
    </div>

    </form>
</div>
<script>
function OnProgress(event, position, total, percentComplete)    
    //Progress bar
    console.log(total);
    $('#pb').width(percentComplete + '%') //update progressbar percent complete
    $('#pt').html(percentComplete + '%'); //update status text

function beforeSubmit()
    console.log('ajax start');

function afterSuccess(data)
    console.log(data);

$(document).ready(function(e) 
    $('#upload_file').submit(function(event)
        event.preventDefault();
        var filedata = document.getElementById("file");
        formdata = new FormData();
        var i = 0, len = filedata.files.length, file;
         for (i; i < len; i++) 
            file = filedata.files[i];
            formdata.append("file[]", file);
        
        formdata.append("json",true);
        $.ajax(
            url: "global.func/file_upload.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            dataType:"JSON",
            xhr: function() 
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            ,
            beforeSubmit: beforeSubmit,
            uploadProgress:OnProgress, 
            success: afterSuccess,
            resetForm: true
        );
    );
);
</script>

图片上传工作正常,数组发送到 ajax 但进度条没有移动。事实上,调用需要产生这个的两个函数的console.log 也不会出现。有没有正确的方法来调用我的 ajax 请求中的函数,以使这个进度条工作。

beforeSubmit: beforeSubmit, 上传进度:OnProgress, 成功:afterSuccess,

请注意,当控制台显示我的数据时,此功能“成功:afterSuccess”正在工作。

【问题讨论】:

您为什么不检查 Eskinder 的回答?对我来说它似乎更完整。 【参考方案1】:

这是你的 HTML 表单

<form method="post" action="uploadImages.php" name ='photo' id='imageuploadform' enctype="multipart/form-data">
        <input hidden="true" id="fileupload" type="file" name="image[]" multiple >

        <div id ="divleft">
            <button id="btnupload"></button>

        </div>    

    </form>

这是你的 JQuery 和 ajax。 默认情况下,fileInput 是隐藏的。

点击上传按钮

$("#btnupload").click(function(e) 

    $("#fileupload").click();
    e.preventDefault();

);


$('#fileupload').change(function (e) 

    $("#imageuploadform").submit();
    e.preventDefault();

);

$('#imageuploadform').submit(function(e) 

    var formData = new FormData(this);

    $.ajax(
        type:'POST',
        url: 'ajax/uploadImages',
        data:formData,
        xhr: function() 
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload)
                    myXhr.upload.addEventListener('progress',progress, false);
                
                return myXhr;
        ,
        cache:false,
        contentType: false,
        processData: false,

        success:function(data)
            console.log(data);

          alert('data returned successfully');

        ,

        error: function(data)
            console.log(data);
        
    );

    e.preventDefault();

);


function progress(e)

    if(e.lengthComputable)
        var max = e.total;
        var current = e.loaded;

        var Percentage = (current * 100)/max;
        console.log(Percentage);


        if(Percentage >= 100)
        
           // process completed  
        
      
 

您的 php 代码如下所示

<?php

header('Content-Type: application/json');

       $valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
        $max_size = 30000 * 1024; // max file size in bytes

        $json = array();

            if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
            
                for($i=0;$i<count($_FILES['image']['tmp_name']);$i++)
                
                    $path="image/uploads/photos/";

                    if(is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
                    
                      // get uploaded file extension
                      $ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
                      // looking for format and size validity
                          if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
                          
                                  // unique file path
                                  $uid = uniqid();
                                  $date = date('Y-m-d-H-i-s');
                                  $path = $path ."image_" .$date. '_' . $uid . "." .$ext;

                                  $returnJson[]= array("filepath"=>$path);

                                  $filename = "image_" . $date . "_" .$uid . "." . $ext;
                                  $this->createthumb($i,$filename);

                                    // move uploaded file from temp to uploads directory
                                  if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
                                  
                                    //$status = 'Image successfully uploaded!';
                                      //perform sql updates here

                                  
                                  else 
                                    $status = 'Upload Fail: Unknown error occurred!';
                                  


                          
                          else 
                            $status = 'Upload Fail: Unsupported file format or It is too large to upload!';
                          
                    
                    else 
                      $status = 'Upload Fail: File not uploaded!';
                    
                
              
            else 
              $status = 'Bad request!';
            


            echo json_encode($json);

?>

【讨论】:

在测试这个本地主机时,我只得到了 100% 的事件。本地上传自然是极快的。限制网络以查看增量事件。 与@Gunslinger 相同,但我正在发送到远程服务器。使用 5MB 或更大的文件调用会立即按预期进行。但是,使用 2MB 左右的小(呃)文件永远不会调用进度。大约有 10 秒的延迟,然后用 100 调用进度... 当然,本地上传时是这样的。【参考方案2】:

您必须使用自定义 XMLHttpRequest 才能通过 AJAX 和 jQuery 执行此操作。这里有一个例子:How can I upload files asynchronously?

【讨论】:

是 xhr: function() 而不是 uploadprogress 来处理这个问题,谢谢

JQuery AJAX 上传文件不适用于超过 10 MB 的文件

...选择了一个文件,我想上传文件(通过PHP文件)并向用户显示上传进度。我尝试使用$.aj 查看详情

java多文件上传显示进度条

用java或者js实现对多文件上传,并显示进度条,可以只显示总进度。手上有类似代码的朋友联系我,扣-15080818,跪求!使用  apachefileupload  ,springMVC  jquery1.6x,bootstrap 实现一个带进度条的多文件上传,由于fileupload的局限,暂... 查看详情

使用 jQuery $.ajax 和 Spring Boot 上传图片的进度条

】使用jQuery$.ajax和SpringBoot上传图片的进度条【英文标题】:ProgressbarforanimageuploadwithjQuery$.ajaxandSpringBoot【发布时间】:2018-01-0619:41:49【问题描述】:我在$.ajax帖子中设置进度条时遇到问题,该帖子通过带有Spring框架的@Controller将... 查看详情

vue多文件上传进度条进度不更新问题

...一个多图片上传的组件,需求是做到多文件依次上传,并显示上传进度条。逻辑部分实现了以后,在更新进度条视图的时候出现一点问题:动态计算生产的进度progress属性不会自动更新。原来 查看详情

CodeIgniter 上传进度

...19【问题描述】:我正在尝试使用CI2.1.3上传带有进度条的文件。我已经让文件上传一切正常,但是获得这个文件进度并不容易。我查看了大量具有不同解决方案的指南,但它们似乎都不起作用,因为大多数都非常过时(2008年左... 查看详情

如何在jsp和servlet中显示文件上传进度条并实现了多部分过滤器?

】如何在jsp和servlet中显示文件上传进度条并实现了多部分过滤器?【英文标题】:Howtoshowafileuploadprogressbarinjspandservletwithamultipartfilterimplemented?【发布时间】:2013-02-2715:57:41【问题描述】:我正在使用jsp和servlet处理文件上传任务... 查看详情

中止多文件上传 AJAX 请求

...【问题描述】:我正在尝试使用进度条中止多文件上传,显示过程状态。我想要实现的是在中止按钮单击时完全中止多个文件上传;停止进度条并清除在最初触发的多文件上传过程中可能已上传的每个文件。下面是我的代码:var... 查看详情

elementel-upload自定义上传显示进度条,多文件上传进度(代码片段)

<template><div><el-uploadclass="upload-demo"ref="upload":multiple="false"action="void":http-request="customUpload":on-remove="handleRemove":on-progress="progressA":file-list="fileList"multiple:auto-upload="true"><el-buttonslot="trigger"size="small"type="primary">选取文件&... 查看详情

jQuery / ajax 上传图片并保存到文件夹

...问题描述】:更新以下代码我发现了一些能够上传图片并显示其缩略图的代码。但是,我也想将图像保存到特定文件夹。我可以使用哪些jQuery代码或ajax代码将原始图像保存到我选择的文件夹中?这是现场演示:http://jsfiddle.net/dn9... 查看详情

哪个javascript框架支持ajax方式的文件上传

...上传插件。支持分块、拖拽、图像缩放、限制文件大小、显示上传进度等。5.UploadifyUploadify是一个jQuery插件,帮助你在网站中轻松添加多文件上传功能,提供了两个版本(HTML5、Flash)。支持多文件上传、拖拽、实时进度显示,提... 查看详情

前端上传文件实时显示进度条和上传速度的工作原理是怎样的?

参考技术A后端的责任。前端上传文件实时显示进度条和上传速度的工作原理就是后端的责任,在Django中实现需要重载上传文件的函数,在上传时文件是被分成数个MB的chunk处理的,每次都会调用这个上传函数。也就是说,每处理... 查看详情

springmvc带进度条的多文件上传

1、关于文件上传进度条的实现在说SpringMVC文件上传尤其是带滚动条之前先用servlet做一个简单的文件上传并返回进度信息这样的功能。(1)需要两个包:commons-fileupload-1.3.1.jarcommons-io-1.4.jar上面这两个包是Apache推出的... 查看详情

jqueryajax实现上传文件代码,带进度条

原文:jqueryajax实现上传文件代码,带进度条 源代码下载地址:http://www.zuidaima.com/share/1550463291116544.htmajax上传文件代码,带进度条的。首页http://localhost:端口/项目名/common/test.htm上传中标签: jquery ajax 上传  查看详情

html文件上传

...的判断。如果我们是用户,当我们上传了一张图片,却只显示了几个文字,是不是很不爽,那我们怎么来实现预览功能呢?我们可以使用FileReader将图像转换为二进制字符串,然后添加load事件监听,在文件上传成功后获取二进制... 查看详情

jqueryajax实现上传文件代码,带进度条

原文:jqueryajax实现上传文件代码,带进度条 源代码下载地址:http://www.zuidaima.com/share/1550463291116544.htmajax上传文件代码,带进度条的。首页http://localhost:端口/项目名/common/test.htm上传中标签: jquery ajax 上传 ... 查看详情

Flutter Web 多部分formdata文件上传进度条

】FlutterWeb多部分formdata文件上传进度条【英文标题】:FlutterWebmultipartformdatafileuploadprogressbar【发布时间】:2021-05-1812:46:12【问题描述】:我正在使用Flutterweb和strapiheadlesscms作为后端。我能够成功发送文件,但想要它的进度指示。... 查看详情

在 JQuery 中通过 AJAX 上传文件

】在JQuery中通过AJAX上传文件【英文标题】:FileUploadviaAJAXwithinJQuery【发布时间】:2010-12-1318:05:13【问题描述】:我是JQueryAJAX的新手。我想使用jquery实现文件上传。是否可以使用JQuery、AJAX进行文件上传并将其发送到可以使用apache... 查看详情

阿里云oss小文件上传进度显示

对阿里云OSS上传小文件时的进度,想过两个方法:一是。通过多线程监測Inputstream剩余的字节数来计算,可是由于Inputstream在两个线程中共用,假设上传线程将Inputstream关闭,在监測线程就会报“句柄无效”的错误,甚至会导致上... 查看详情