使用jQuery,AJAX和PHP上传图像

时间:2016-12-14 14:30:41

标签: php jquery html ajax

我尝试从PC /手机中选择一张图片,然后点按一下按钮就将其上传到服务器但由于某种原因我无法获取所选图片的值(名称) - {{1在PHP页面内。我可以使用两个按钮轻松完成,一个用于浏览设备上的图像,另一个用于上传,但我真的需要一键按钮才能完成这两个步骤。

我的源代码:

HTML

$_FILES["pictureCapture"]["name"]

jQuery + AJAX

<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>

PHP

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

请你帮我解决这个问题!

2 个答案:

答案 0 :(得分: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',
    ...

答案 1 :(得分:0)

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

或者适用于您的情况:

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