【问题标题】:Passing an image file is unsuccessful using AJAX [duplicate]使用 AJAX 传递图像文件失败 [重复]
【发布时间】:2016-03-29 13:37:32
【问题描述】:

我遇到了一个错误,上传图像文件时我无法通过 AJAX 传递图像文件。这是我的代码

AJAX

    var file = $("#thumbnail").get(0).files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file", file);

alert (formdata);

    $.ajax({
        url: "php/post-check.php",
        type: "POST",
        data: {
            title: title,
            thumbnail: formdata
        },
        success: function (data) {
            $("div#postresult").removeClass("alert alert-danger");
            $("div#postresult").html(data);
        }
    });

PHP

<?php 
        $target_dir = "../thumbnail-pictures/";
        $target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
        $uploadOk = 1;
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

        if (file_exists($target_file)) {
            echo "Sorry, thumbnail file already exists. <br>";
            $uploadOk = 0;
        }

        if ($_FILES["thumbnail"]["size"] > 1000000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }

        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }

        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded, ";

        } else {
            if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {
                
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
        ?>

HTML

<form action="" method="post" enctype="multipart/form-data" id="newpost">
                <div class="col-lg-12">
                        <div class="form-group">
                            <label>Title</label>
                            <input class="form-control" name="title" id="title" required>
                            
                        </div>

                        <div class="form-group">
                            <label>Video Thumbnail **Only JPEG & PNG is accepted**</label>
                            <input type="file" name="thumbnail" id="thumbnail" accept="image/png, image/gif, image/jpeg" >
                        </div>

PHP 代码本身运行良好,所以我认为问题出在 AJAX 部分,但是我不确定如何解决这个问题。感谢您提供的任何帮助!

【问题讨论】:

标签: javascript php html ajax


【解决方案1】:

问题应该出在参数processData上,请加参数processData: false, 到您的 ajax 请求并尝试在 php 上获取您的图像。

            $.ajax({
                url: formURL,
                type: form.attr('method'),
                dataType: 'json',
                data: formData,//form.serialize(),
                processData: false,  // tell jQuery not to process the data
                contentType: false,   // tell jQuery not to set contentType
                beforeSend: function(){},
                success: function(data, textStatus, jqXHR) {},
                error: function(jqXHR, textStatus, errorThrown) 
               {
                  alert(jqXHR+ textStatus+ errorThrown);
                },
              complete: function(){}
                });

希望有帮助。祝你好运

【讨论】:

    【解决方案2】:

    将您的输入正确放置在一个表单中,然后使用FormData() 将整个表单发送出去。我会建议这样的事情:

    <form method="post" enctype="multipart/formdata" id="myForm">
       <input type="text" name="title" />
       <input type="file" name="thumbnail" />
    </form>
    

    用js构建和发送数据:

    var form = document.getElementById('myForm');
    var formData = new FormData(form);
    
    alert (formdata);
    
    $.ajax({
        url: "php/post-check.php",
        type: "POST",
        data: formData,
        success: function (data) {
            $("div#postresult").removeClass("alert alert-danger");
            $("div#postresult").html(data);
        }
    });
    

    现在你可以像这样在 php 中获取数据:

    $title = $_POST['title'];
    $thumb = $_FILES['thumbnail'];
    $tmp_file_path = $thumb['tmp_name'];
    

    【讨论】:

      【解决方案3】:

      您可以像这样使用 ajaxForm() 异步发布整个表单:

      $("#newpost").ajaxForm({
          success: function(data) {
              $("div#postresult").removeClass("alert alert-danger");
              $("div#postresult").html(data);
          },
          error: function(a, textStatus, exception) {
      
          }
      });
      

      AjaxForm 不是核心 JQuery 的一部分,但您可以找到源代码 here 和文档 here

      【讨论】:

      • jQuery 不提供 ajaxForm 表单方法。
      • 没错。然而,问题只是说明答案应该使用 ajax 而不是 JQuery 核心功能。我编辑了我的答案
      • @Quentin 你介意更正否决票吗?
      猜你喜欢
      • 2012-10-12
      • 2014-10-19
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多