【问题标题】:Who to upload image using jQuery error with sending image using ajax谁使用 jQuery 上传图像错误并使用 ajax 发送图像
【发布时间】:2019-04-21 14:36:35
【问题描述】:

当我尝试使用 jQuery 和 ajax 上传图片时出错。

这是我的html:

<label for="img_add_galery">
                    <a class="add">
                        <img click="image_galery" src="../../img/ui/black.png" alt="images">
                    </a>
                  </label>
                </div>
                <input type="file" id="img_add_galery" name="img_add_galery" style="display:none;"/>

这是我的 js:

$(document).on('change','#img_add_galery',function(){
    var property = document.getElementById('img_add_galery').files[0];
    var image_name = property.name;
    var image_extension = image_name.split('.').pop().toLowerCase();
    if(jQuery.inArray(image_extension, ['gif','png','jpg','jpeg']) == -1)
    {
      alert('invalid image type');
    }
    var image_size = property.size;
    if(image_size > 2000000000000)
    {
      alert('image is to big');
    }
    else
    {
      console.log(property);
        var form_data = new FormData();
        form_data.append("file", property);
        $.ajax({
          url: "traitement/add_image_galery.php",
          method: "POST",
          data: form_data,
          contentType:false,
          cache:false,
          processData:false,
          success:function(data)
          {
            $(".tz-gallery").children().append(data);
        }
      })
  }
})

和我的 php

var_dump($_FILES["img_add_galery"]["name"]);

if($_FILES["file_img"]["name"] != '')

{

  $test = explode(".",$_FILES["file_img"]["name"]);

  $extension = end($test);

  $name = rand(1,9999) . '.' . $extension;

  $location = '../../../img/galerie/'.$name;

  move_uploaded_file($_FILES["file_img"]["tmp_name"],$location);

  echo '<div class="col-sm-6 col-md-4">
      <a class="delete" img="'.$location.'">
          <img click="image_galery" src="'.$location.'" alt="images">
      </a>
  </div>';
}

【问题讨论】:

  • 您尝试在上传时在 $.ajax POST 中添加选项“enctype: 'multipart/form-data'”。

标签: php jquery image upload


【解决方案1】:

当您将文件附加到您的 FormData 对象时,您使用 file 作为其名称,但在 PHP 中您使用 file_img,两者必须匹配。

$_FILES["file"]["name"]

事实上,我认为您应该在任何地方使用相同的名称以避免混淆

<input type="file" id="img_add_galery" name="img_add_galery" style="display:none;"/>
form_data.append("img_add_galery", property);
$_FILES["img_add_galery"]["name"]

另外,如果你想检查文件数组中发生了什么,你应该转储整个文件var_dump($_FILES);

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2023-04-01
    • 2014-03-23
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多