【问题标题】:Upload image using jQuery, AJAX and PHP使用 jQuery、AJAX 和 PHP 上传图片
【发布时间】:2016-12-14 14:30:40
【问题描述】:

我正在尝试从 PC/移动设备中选择一张图片,然后单击一键将其上传到服务器,但由于某种原因,我无法获取所选图片的值(名称) - PHP 页面内的 $_FILES["pictureCapture"]["name"]。我可以使用两个按钮轻松完成此操作,一个用于浏览我设备上的图像,第二个用于上传,但这两个过程我真的需要单击一个按钮。

我的源代码:

HTML

<form action="" method="post" enctype="multipart/form-data" onsubmit="test3()">
    Select image to upload:
    <input type="file" name="pictureCapture" id="pictureCapture" accept="image/*; capture=camera" style="visibility:hidden;" onchange="test2();"/>
    <button type="button" id="uploadPhotoFromCamera" onclick="test();">Choose an image</button>
    <input id="uploadPhotoToServer" type="submit" value="Upload Image" name="submit" style="visibility:hidden;"/>
</form>

jQuery + AJAX

function test(){  
   event.preventDefault();
   $("#pictureCapture").trigger("click");
}

function test2(){   
    $("#uploadPhotoToServer").trigger("click");
}

   function test3(){
      event.preventDefault();

      var formData = new FormData();
      var fileInput = document.getElementById('pictureCapture');
      formData.append(fileInput.files[0].name, fileInput.files[0]);   

      $.ajax({
          url : "upload.php", // Url to which the request is send
          type : "POST", // Type of request to be send, called as method
          data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
          cache : false, // To unable request pages to be cached
          processData : false, // To send DOMDocument or non processed data file it is set to false
          contentType: 'multipart/form-data',
        success : function(result) // A function to be called if request succeeds
        {
            alert(result);
        }
    });
}

PHP

$target_dir = "uploads/";
$target_file = $target_dir .date('d-m-Y-H-i-s').'-'. basename($_FILES["pictureCapture"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["pictureCapture"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

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

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["pictureCapture"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["pictureCapture"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

请你帮我解决这个问题!

【问题讨论】:

  • 也许用 test2 来触发表单提交?
  • @dimis283,我知道它会按照您建议的方式工作,但我需要使用 AJAX 才能在我的 html 页面中显示错误或成功消息
  • 我的意思是这样的 airpair.com/js/jquery-ajax-post-tutorial 查看 2 AJAX POST 示例,jQuery 方式
  • 附注 - 不要使用getimagesize 来检查文件是否是有效的图像文件。 php.net/manual/en/…

标签: php jquery html ajax


【解决方案1】:

你需要用你的文件数据填充你的 FormData():

var formData = new FormData();
$.each($('pictureCapture')[0].files, function(key, value) {
    formData.append(key, value);
});

在您的 jQuery ajax 调用中添加将您的 contentType 更改为 multipart:

$.ajax({
    ...
    data: formData, 
    ...
    contentType: 'multipart/form-data',
    ...

【讨论】:

  • 您删除了contentType: false 行吗?
  • 是的,我做了,但仍然没有!
  • 您还忘记将文件数据添加到 FormData 对象。检查编辑。
  • 我现在遇到了这个错误 - Uncaught TypeError: Cannot read property 'files' of undefined
  • 看看我更新的脚本,还是抓不到文件名:(
【解决方案2】:

为什么不在文件输入上使用 onchange 自动提交表单呢?一旦他们选择了一个文件,它就会为他们提交图像。这是jsfiddle

或适用于您的情况:

$(document).ready(function(){
    $('#pictureCapture').change(function(){
        this.form.submit();
    });
});

【讨论】:

  • 很公平,但我需要使用 AJAX 才能在我的 html 页面中显示错误或成功消息
猜你喜欢
  • 2015-05-05
  • 2019-02-06
  • 2015-09-01
  • 2010-12-06
  • 2014-12-02
  • 2016-08-10
相关资源
最近更新 更多