使用 AJAX、PHP 和 jQuery 上传多张图片 [英] Upload multiple image using AJAX, PHP and jQuery

查看:32
本文介绍了使用 AJAX、PHP 和 jQuery 上传多张图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 AJAX 上传多张图片时遇到很多问题.我写了这段代码:

HTML

<div id="drop" class="drop-area"><div class="drop-area-label">将图片拖到此处

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

<ul class="gallery-image-list" id="上传"><!-- 文件上传将显示在这里--></表单><div id="listTable"></div>

jQuery/AJAX

$(document).on("change", "input[name^='file']", function(e){e.preventDefault();var This = this,display = $("#uploads");//列出所有文件数据$.each(This.files, function(i, obj){//为每个图像异步运行脚本(功能(一){//从输入文件中获取数据var file = This.files[i],名称 = 文件名,大小 = 文件大小,类型 = 文件.类型,lastModified = file.lastModified,lastModifiedDate = file.lastModifiedDate,webkitRelativePath = file.webkitRelativePath,切片 = file.slice,我 = 我;//调试/*var acc = []$.each(file, function(index, value) {acc.push(index + ":" + value);});警报(JSON.stringify(acc));*/$.ajax({url:'/ajax/upload.php',contentType: "multipart/form-data",数据:{图片":{名称":名称,尺寸":尺寸,类型":类型,"lastModified":lastModified,"lastModifiedDate":lastModifiedDate,"webkitRelativePath":webkitRelativePath,//切片":切片,}},类型:POST",//自定义 XMLHttpRequestxhr:函数(){var myXhr = $.ajaxSettings.xhr();//检查上传属性是否存在如果(myXhr.upload){//用于处理上传进度myXhr.upload.addEventListener("progress",progressHandlingFunction, false);}返回 myXhr;},缓存:假,成功:功能(数据){//加载ajax数据$("#listTable").append(data);}});//显示进度函数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("宽度", perc+"%");}}//显示文件列表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>');})(一世);});});

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

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

谢谢!

解决方案

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

html

<div class="drop-area-label">将图片拖放到此处</div>

<br/><form id="上传"><input type="file" name="file" id="file" multiple="true" accepts="image/*"/><ul class="gallery-image-list" id="上传"><!-- 文件上传将显示在这里--></表单><div id="listTable"></div>

css

 #uploads {显示:块;位置:相对;}#上传李{列表样式:无;}#降低 {宽度:90%;高度:100px;填充:0.5em;向左飘浮;边距:10px;边框:8px 灰色虚线;}#drop.hover {边框:8px 绿色虚线;}#drop.err {边框:8px 点缀橙红色;}

js

var display = $("#uploads");//缓存 `#uploads`, `this` 在 `$.ajax()`var droppable = $("#drop")[0];//缓存 `#drop` 选择器$.ajaxSetup({上下文:显示,内容类型:应用程序/json",数据类型:json",beforeSend:函数(jqxhr,设置){//预处理`文件`var 文件 = JSON.parse(decodeURIComponent(settings.data.split(/=/)[1]));//为每个 `file` 添加 `progress` 元素var progress = $("", {"class": "file-" + (!!$("progress").length?$("progress").length:0"),分钟":0,最大":0,价值":0,数据名称":文件名});this.append(progress, file.name + "
");jqxhr.name = progress.attr("class");}});var processFiles = function processFiles(event) {event.preventDefault();//处理 `input[type=file]`, `droppable` `file`var 文件 = event.target.files ||event.dataTransfer.files;var 图像 = $.map(files, function (file, i) {var reader = new FileReader();var dfd = new $.Deferred();reader.onload = 函数 (e) {dfd.resolveWith(file, [e.target.result])};reader.readAsDataURL(new Blob([file], {类型":file.type}));返回 dfd.then(函数(数据){返回 $.ajax({类型:POST",url: "/echo/json/",数据: {文件":JSON.stringify({文件":数据,名称":this.name,大小":this.size,类型":this.type})},xhr:函数(){//做 `progress` 事件var 上传 = this.context;var progress = this.context.find("progress:last");var xhrUpload = $.ajaxSettings.xhr();如果(xhrUpload.upload){xhrUpload.upload.onprogress = 函数 (evt) {进度.属性({最大":evt.total,值":evt.loaded})};xhrUpload.upload.onloadend = 函数(evt){var progressData = progress.eq(-1);console.log(progressData.data("name")+ "上传完成...");var img = 新图片;$(img).addClass(progressData.eq(-1).attr("类"));img.onload = 函数 () {如果(this.complete){控制台日志(progressData.data("名称")+ " 预览加载中...");};};uploads.append("<br/><li>", img, "</li><br/>");};}返回 xhrUpload;}}).then(function (data, textStatus, jqxhr) {控制台日志(数据)this.find("img[class=" + jqxhr.name + "]").attr("src", data.file).before("" + data.name + "
");返回数据}, 函数 (jqxhr, textStatus, errorThrown) {控制台日志(错误抛出);返回错误抛出});})});$.when.apply(display, images).then(function () {var 结果 = $.makeArray(arguments);console.log(result.length, "上传完成");}, 函数 err(jqxhr, textStatus, errorThrown) {console.log(jqxhr, textStatus, errorThrown)})};$(文件).on("change", "input[name^=file]", processFiles);//处理 `droppable` 事件droppable.ondragover = 函数(){$(this).addClass("悬停");返回假;};droppable.ondragend = 函数(){$(this).removeClass("悬停")返回假;};droppable.ondrop = 函数 (e) {$(this).removeClass("悬停");var image = Array.prototype.slice.call(e.dataTransfer.files).every(function (img, i) {返回/^image/.test(img.type)});e.preventDefault();//如果`file`,文件类型`image`,处理`file`if (!!e.dataTransfer.files.length && image) {$(this).find(".drop-area-label").css(颜色",蓝色").html(函数(我,html){$(this).delay(3000, "msg").queue("msg", function () {$(this).css("color", "initial").html(html)}).dequeue("msg");return "文件丢失,正在处理文件上传...";});进程文件(e);} 别的 {//如果删除了 `file` _not_ `image`$(这个).removeClass("悬停").addClass("错误").find(".drop-area-label").css(颜色",深红色").html(函数(我,html){$(this).delay(3000, "msg").queue("msg", function () {$(this).css("color", "initial").html(html).parent("#drop").removeClass("err")}).dequeue("msg");return "请删除图片文件...";});};};

php

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

I have a lot of problem to upload multiple images using AJAX. I write this code:

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);
    }); 
});

I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.

I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.

Thanks!

解决方案

Try utilizing json to upload , process file object

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, textStatus, 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, textStatus, errorThrown) {
        console.log(jqxhr, textStatus, 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, html) {
            $(this).delay(3000, "msg").queue("msg", function () {
                $(this).css("color", "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/

这篇关于使用 AJAX、PHP 和 jQuery 上传多张图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆