使用 AJAX上传多个图像有很多问题.我写这段代码:

HTML

<form id="upload" method="post" enctype="multipart/form-data">
    <div id="drop" class="drop-area">
        <div class="drop-area-label">
            Drop image here
        </div>
        <input type="file" name="file" id="file" multiple/>
    </div>

    <ul class="gallery-image-list" id="uploads">
    <!-- The file uploads will be shown here -->
    </ul>
</form>
<div id="listTable"></div>

jQuery的/ AJAX

$(document).on("change","input[name^='file']",function(e){
    e.preventDefault();
    var This    =   this,display =   $("#uploads");

    // list all file data
    $.each(This.files,function(i,obj){
        // for each image run script asynchronous
        (function(i) {
            // get data from input file
            var file = This.files[i],name = file.name,size = file.size,type = file.type,lastModified        =   file.lastModified,lastModifiedDate    =   file.lastModifiedDate,webkitRelativePath  =   file.webkitRelativePath,slice               =   file.slice,i = i;

            // DEBUG
       /*
            var acc = []
            $.each(file,function(index,value) {
                acc.push(index + ": " + value);
            });
            alert(JSON.stringify(acc));
        */

            $.ajax({
                url:'/ajax/upload.PHP',contentType: "multipart/form-data",data:{
                        "image":
                        {
                            "name":name,"size":size,"type":type,"lastModified":lastModified,"lastModifiedDate":lastModifiedDate,"webkitRelativePath":webkitRelativePath,//"slice":slice,}
                    },type: "POST",// Custom XMLHttpRequest
                xhr: function() {
                    var myXhr = $.ajaxSettings.xhr();
                    // Check if upload property exists
                    if(myXhr.upload)
                    {
                        // For handling the progress of the upload
                        myXhr.upload.addEventListener("progress",progressHandlingFunction,false); 
                    }
                    return myXhr;
                },cache: false,success : function(data){
                    // load ajax data
                    $("#listTable").append(data);
                }
            });
            // display progress
            function progressHandlingFunction(e){
                if(e.lengthComputable){
                    var perc = Math.round((e.loaded / e.total)*100);
                    perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
                $("#progress"+i+" > div")
                    .attr({"aria-valueNow":perc})
                        .css("width",perc+"%");
                }
            }
            // display list of files
            display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
                    +'<div class="progress-bar" role="progressbar" aria-valueNow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
                    +'</div></div>');
        })(i);
    }); 
});

我尝试了各种版本,但我从未成功通过ajax发送多个数据.我已经尝试过你在上面看到的内容,现在我只获得了POST信息.我理解为什么我会收到POST,但我需要发送FILES信息,我不知道我哪里错了.

我第一次使用ajax工作并经常在大多数项目中使用它,但我从来没有用过发送多个文件而现在困扰我.

谢谢!

解决方法

尝试利用json上传,处理文件对象

HTML

<div id="drop" class="drop-area ui-widget-header">
  <div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
  <input type="file" name="file" id="file" multiple="true" accepts="image/*" />
  <ul class="gallery-image-list" id="uploads">
    <!-- The file uploads will be shown here -->
  </ul>
</form>
<div id="listTable"></div>

CSS

#uploads {
      display:block;
      position:relative;
  } 

  #uploads li {
      list-style:none;
  }

  #drop {
      width: 90%;
      height: 100px;
      padding: 0.5em;
      float: left;
      margin: 10px;
      border: 8px dotted grey;
  }

  #drop.hover {
      border: 8px dotted green;
  }

  #drop.err {
      border: 8px dotted orangered;
  }

JS

var display = $("#uploads"); // cache `#uploads`,`this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
    context: display,contentType: "application/json",dataType: "json",beforeSend: function (jqxhr,settings) {
        // pre-process `file`
        var file = JSON.parse(
                   decodeURIComponent(settings.data.split(/=/)[1])
                   );
        // add `progress` element for each `file`
        var progress = $("<progress />",{
                "class": "file-" + (!!$("progress").length 
                         ? $("progress").length 
                         : "0"),"min": 0,"max": 0,"value": 0,"data-name": file.name
        });
        this.append(progress,file.name + "<br />");
        jqxhr.name = progress.attr("class"); 
    }
});

var processFiles = function processFiles(event) {
    event.preventDefault();
    // process `input[type=file]`,`droppable` `file`
    var files = event.target.files || event.dataTransfer.files;
    var images = $.map(files,function (file,i) {
        var reader = new FileReader();
        var dfd = new $.Deferred();
        reader.onload = function (e) {
            dfd.resolveWith(file,[e.target.result])
        };
        reader.readAsDataURL(new Blob([file],{
            "type": file.type
        }));
        return dfd.then(function (data) {
            return $.ajax({
                type: "POST",url: "/echo/json/",data: {
                    "file": JSON.stringify({
                            "file": data,"name": this.name,"size": this.size,"type": this.type
                    })
                },xhr: function () {
                    // do `progress` event stuff
                    var uploads = this.context;
                    var progress = this.context.find("progress:last");
                    var xhrUpload = $.ajaxSettings.xhr();
                    if (xhrUpload.upload) {
                        xhrUpload.upload.onprogress = function (evt) {
                            progress.attr({
                                    "max": evt.total,"value": evt.loaded
                            })
                        };
                        xhrUpload.upload.onloadend = function (evt) {
                            var progressData = progress.eq(-1);
                            console.log(progressData.data("name")
                                    + " upload complete...");
                            var img = new Image;
                            $(img).addClass(progressData.eq(-1)
                            .attr("class"));
                            img.onload = function () {
                                if (this.complete) {
                                  console.log(
                                      progressData.data("name")
                                      + " preview loading..."
                                  );
                                };

                            };
                        uploads.append("<br /><li>",img,"</li><br />");
                        };
                    }
                    return xhrUpload;
                }
            })
            .then(function (data,textStatus,jqxhr) {
                console.log(data)
                this.find("img[class=" + jqxhr.name + "]")
                .attr("src",data.file)
                .before("<span>" + data.name + "</span><br />");
                return data
            },function (jqxhr,errorThrown) {
                console.log(errorThrown);
                return errorThrown
            });
        })
    });
    $.when.apply(display,images).then(function () {
        var result = $.makeArray(arguments);
        console.log(result.length,"uploads complete");
    },function err(jqxhr,errorThrown) {
        console.log(jqxhr,errorThrown)
    })
};

$(document)
.on("change","input[name^=file]",processFiles);
// process `droppable` events
droppable.ondragover = function () {
    $(this).addClass("hover");
    return false;
};

droppable.ondragend = function () {
    $(this).removeClass("hover")
    return false;
};

droppable.ondrop = function (e) {
    $(this).removeClass("hover");
    var image = Array.prototype.slice.call(e.dataTransfer.files)
        .every(function (img,i) {
        return /^image/.test(img.type)
    });
    e.preventDefault();
    // if `file`,file type `image`,process `file`
    if (!!e.dataTransfer.files.length && image) {
            $(this).find(".drop-area-label")
            .css("color","blue")
            .html(function (i,html) {
            $(this).delay(3000,"msg").queue("msg",function () {
                $(this).css("color","initial").html(html)
            }).dequeue("msg");
            return "File dropped,processing file upload...";
        });
        processFiles(e);
    } else {
            // if dropped `file` _not_ `image`
            $(this)
            .removeClass("hover")
            .addClass("err")
            .find(".drop-area-label")
            .css("color","darkred")
            .html(function (i,"initial").html(html)
                .parent("#drop").removeClass("err")
            }).dequeue("msg");
            return "Please drop image file...";
        });
    };
};

PHP

<?PHP
  if (isset($_POST["file"])) {
    // do PHP stuff
    // call `json_encode` on `file` object
    $file = json_encode($_POST["file"]);
    // return `file` as `json` string
    echo $file;
  };

jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

javascript – 使用AJAX,PHP和jQuery上传多个图像的更多相关文章

  1. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. 从iOS应用程序发送帖子到PHP脚本不工作…简单的解决方案就像

    我之前已经做了好几次了但是由于某些原因我无法通过这个帖子…我尝试了设置为_POST且没有的变量的PHP脚本……当它们未设置为发布时它工作精细.这是我的iOS代码:这里是PHP的一大块,POST变量不在正确的位置?我想这对于更有经验的开发人员来说是一个相当简单的答案,感谢您的帮助!解决方法$_POST是一个数组,而不是一个函数.您需要使用方括号来访问数组索引:

  3. 在IOS9中的Cordova应用程序使用JQuery / Javascript的window.history问题

    在两个测试用例中唯一改变的是Cordova.js.解决方法我看到这是几个星期前,但我会发布这个,以防其他人遇到它.听起来它可能与iOS9中的哈希更改生成的导航事件有关.如果是这样,可以将其添加到index.html以禁用哈希侦听:

  4. iOS 5上的jQuery事件

    解决方法在Apple开发论坛上由一个人回答:我需要在将元素添加到DOM之后才绑定(),如下所示:

  5. 应用程序关闭时的iOS任务

    我正在构建一个应用程序,通过ajax将文件上传到服务器.问题是用户很可能有时不会有互联网连接,并且客户希望在用户重新连接时安排ajax调用.这可能是用户在离线时安排文件上传并关闭应用程序.应用程序关闭时可以进行ajax调用吗?

  6. swift学习2 元组 tuples

    swift中出现了一种新的数据结构,非常牛掰的元组tuples如果懂PHP的猿,会发现这个元组和PHP的数组非常类似,同样是可以默认不指定key,也可以指定key目前的学习疑问是,如何进行元组的遍历?

  7. 尝试使用swift mailer,gmail smtp,php发送邮件

    这里是我的代码:在运行时出现此错误…

  8. android – Phonegap本地构建 – jquery ajax错误:readystate 0 responsetext status 0 statustext error

    解决方法您是否在索引文件中包含了内容安全元标记?

  9. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  10. 设置焦点到输入框和显示Android键盘使用jquery手机在pageshow

    我正在设置焦点到输入框,并显示Android键盘使用jquery手机网页显示.我从Web上尝试过很多选项.但是没有一个在模拟器和移动设备中都能按预期工作.这是代码:查找屏幕截图以供参考请咨询…解决方法对我有用的解决方案

随机推荐

  1. xe-ajax-mock 前端虚拟服务

    最新版本见Github,点击查看历史版本基于XEAjax扩展的Mock虚拟服务插件;对于前后端分离的开发模式,ajax+mock使前端不再依赖后端接口开发效率更高。CDN使用script方式安装,XEAjaxMock会定义为全局变量生产环境请使用xe-ajax-mock.min.js,更小的压缩版本,可以带来更快的速度体验。

  2. vue 使用 xe-ajax

    安装完成后自动挂载在vue实例this.$ajaxCDN安装使用script方式安装,VXEAjax会定义为全局变量生产环境请使用vxe-ajax.min.js,更小的压缩版本,可以带来更快的速度体验。cdnjs获取最新版本点击浏览已发布的所有npm包源码unpkg获取最新版本点击浏览已发布的所有npm包源码AMD安装require.js安装示例ES6Module安装通过Vue.use()来全局安装示例./Home.vue

  3. AJAX POST数据中文乱码解决

    前端使用encodeURI进行编码后台java.net.URLDecoder进行解码编解码工具

  4. Koa2框架利用CORS完成跨域ajax请求

    实现跨域ajax请求的方式有很多,其中一个是利用CORS,而这个方法关键是在服务器端进行配置。本文仅对能够完成正常跨域ajax响应的,最基本的配置进行说明。这样OPTIONS请求就能够通过了。至此为止,相当于仅仅完成了预检,还没发送真正的请求呢。

  5. form提交时,ajax上传文件并更新到&lt;input&gt;中的value字段

  6. ajax的cache作用

    filePath="+escape;},error:{alert;}});解决方案:1.加cache:false2.url加随机数正常代码:网上高人解读:cache的作用就是第一次请求完毕之后,如果再次去请求,可以直接从缓存里面读取而不是再到服务器端读取。

  7. 浅谈ajax上传文件属性contentType = false

    默认值为contentType="application/x-www-form-urlencoded".在默认情况下,内容编码类型满足大多数情况。在这里,我们主要谈谈contentType=false.在使用ajax上传文件时:在其中先封装了一个formData对象,然后使用post方法将文件传给服务器。说到这,我们发现在JQueryajax()方法中我们使contentType=false,这不是冲突了吗?这就是因为当我们在form标签中设置了enctype=“multipart/form-data”,

  8. 909422229_ajaxFileUpload上传文件

    ajaxFileUpload.js很多同名的,因为做出来一个很容易。我上github搜AjaxFileUpload出来很多类似js。ajaxFileUpload是一个异步上传文件的jQuery插件传一个不知道什么版本的上来,以后不用到处找了。语法:$.ajaxFileUploadoptions参数说明:1、url上传处理程序地址。2,fileElementId需要上传的文件域的ID,即的ID。3,secureuri是否启用安全提交,默认为false。4,dataType服务器返回的数据类型。6,error

  9. AJAX-Cache:一款好用的Ajax缓存插件

    原文链接AJAX-Cache是什么Ajax是前端开发必不可少的数据获取手段,在频繁的异步请求业务中,我们往往需要利用“缓存”提升界面响应速度,减少网络资源占用。AJAX-Cache是一款jQuery缓存插件,可以为$.ajax()方法扩展缓存功能。

  10. jsf – Ajax update/render在已渲染属性的组件上不起作用

    我试图ajax更新一个有条件渲染的组件。我可以确保#{user}实际上是可用的。这是怎么引起的,我该如何解决呢?必须始终在ajax可以重新呈现之前呈现组件。Ajax正在使用JavaScriptdocument.getElementById()来查找需要更新的组件。但是如果JSF没有将组件放在第一位,那么JavaScript找不到要更新的内容。解决方案是简单地引用总是渲染的父组件。

返回
顶部