Upload image using jQuery, AJAX and PHP

前端 未结 2 953
臣服心动
臣服心动 2021-01-28 02:20

I\'m trying to choose an image from PC/mobile and upload it to the server on one button click but for some reason I can\'t grab the value (name) of chosen image - $_FILES[

相关标签:
2条回答
  • 2021-01-28 02:37

    You need to populate your FormData() with your file data:

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

    Add change your contentType to multipart in your jQuery ajax call:

    $.ajax({
        ...
        data: formData, 
        ...
        contentType: 'multipart/form-data',
        ...
    
    0 讨论(0)
  • 2021-01-28 02:38

    Why not just submit the form automatically using onchange on the file input? As soon as they select a file, it will submit the image for them. Here is a jsfiddle.

    Or as is applies to your situation:

    $(document).ready(function(){
        $('#pictureCapture').change(function(){
            this.form.submit();
        });
    });
    
    0 讨论(0)
提交回复
热议问题