Rectangle 27 38

Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
</form>
$_FILES
Array
(
    [media] => Array
        (
            [name] => Array
                (
                    [0] => Galata_Tower.jpg
                    [1] => 518f.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpIQaOYo
                    [1] => /tmp/phpJQaOYo
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 258004
                    [1] => 127884
                )

        )

)

If you do progressive enhancement, using Raphael's JS to submit the files...

var data = new FormData($('input[name^="media"]'));     
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
    data.append(i, file);
});

$.ajax({
    type: ppiFormMethod,
    data: data,
    url: ppiFormActionURL,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
        alert(data);
    }
});

... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:

Array
(
    [0] => Array
        (
            [name] => Galata_Tower.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpAQaOYo
            [error] => 0
            [size] => 258004
        )

    [1] => Array
        (
            [name] => 518f.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpBQaOYo
            [error] => 0
            [size] => 127884
        )

)

That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:

// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );

// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
    data.append(fileInputName+'['+i+']', file);
});

(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)

  • Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
  • The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.

With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.

Sending multipart/formdata with jQuery.ajax - Stack Overflow

jquery ajax file-upload multipartform-data form-data
Rectangle 27 38

Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
</form>
$_FILES
Array
(
    [media] => Array
        (
            [name] => Array
                (
                    [0] => Galata_Tower.jpg
                    [1] => 518f.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpIQaOYo
                    [1] => /tmp/phpJQaOYo
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 258004
                    [1] => 127884
                )

        )

)

If you do progressive enhancement, using Raphael's JS to submit the files...

var data = new FormData($('input[name^="media"]'));     
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
    data.append(i, file);
});

$.ajax({
    type: ppiFormMethod,
    data: data,
    url: ppiFormActionURL,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
        alert(data);
    }
});

... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:

Array
(
    [0] => Array
        (
            [name] => Galata_Tower.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpAQaOYo
            [error] => 0
            [size] => 258004
        )

    [1] => Array
        (
            [name] => 518f.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpBQaOYo
            [error] => 0
            [size] => 127884
        )

)

That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:

// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );

// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
    data.append(fileInputName+'['+i+']', file);
});

(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)

  • Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
  • The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.

With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.

Sending multipart/formdata with jQuery.ajax - Stack Overflow

jquery ajax file-upload multipartform-data form-data
Rectangle 27 37

Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
</form>
$_FILES
Array
(
    [media] => Array
        (
            [name] => Array
                (
                    [0] => Galata_Tower.jpg
                    [1] => 518f.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpIQaOYo
                    [1] => /tmp/phpJQaOYo
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 258004
                    [1] => 127884
                )

        )

)

If you do progressive enhancement, using Raphael's JS to submit the files...

var data = new FormData($('input[name^="media"]'));     
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
    data.append(i, file);
});

$.ajax({
    type: ppiFormMethod,
    data: data,
    url: ppiFormActionURL,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
        alert(data);
    }
});

... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:

Array
(
    [0] => Array
        (
            [name] => Galata_Tower.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpAQaOYo
            [error] => 0
            [size] => 258004
        )

    [1] => Array
        (
            [name] => 518f.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpBQaOYo
            [error] => 0
            [size] => 127884
        )

)

That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:

// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );

// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
    data.append(fileInputName+'['+i+']', file);
});

(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)

  • Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
  • The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.

With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.

Sending multipart/formdata with jQuery.ajax - Stack Overflow

jquery ajax file-upload multipartform-data form-data
Rectangle 27 37

Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
</form>
$_FILES
Array
(
    [media] => Array
        (
            [name] => Array
                (
                    [0] => Galata_Tower.jpg
                    [1] => 518f.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpIQaOYo
                    [1] => /tmp/phpJQaOYo
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 258004
                    [1] => 127884
                )

        )

)

If you do progressive enhancement, using Raphael's JS to submit the files...

var data = new FormData($('input[name^="media"]'));     
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
    data.append(i, file);
});

$.ajax({
    type: ppiFormMethod,
    data: data,
    url: ppiFormActionURL,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
        alert(data);
    }
});

... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:

Array
(
    [0] => Array
        (
            [name] => Galata_Tower.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpAQaOYo
            [error] => 0
            [size] => 258004
        )

    [1] => Array
        (
            [name] => 518f.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpBQaOYo
            [error] => 0
            [size] => 127884
        )

)

That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:

// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );

// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
    data.append(fileInputName+'['+i+']', file);
});

(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)

  • Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
  • The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.

With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.

Sending multipart/formdata with jQuery.ajax - Stack Overflow

jquery ajax file-upload multipartform-data form-data
Rectangle 27 37

Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
</form>
$_FILES
Array
(
    [media] => Array
        (
            [name] => Array
                (
                    [0] => Galata_Tower.jpg
                    [1] => 518f.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpIQaOYo
                    [1] => /tmp/phpJQaOYo
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 258004
                    [1] => 127884
                )

        )

)

If you do progressive enhancement, using Raphael's JS to submit the files...

var data = new FormData($('input[name^="media"]'));     
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
    data.append(i, file);
});

$.ajax({
    type: ppiFormMethod,
    data: data,
    url: ppiFormActionURL,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
        alert(data);
    }
});

... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:

Array
(
    [0] => Array
        (
            [name] => Galata_Tower.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpAQaOYo
            [error] => 0
            [size] => 258004
        )

    [1] => Array
        (
            [name] => 518f.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpBQaOYo
            [error] => 0
            [size] => 127884
        )

)

That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:

// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );

// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
    data.append(fileInputName+'['+i+']', file);
});

(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)

  • Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
  • The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.

With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.

Sending multipart/formdata with jQuery.ajax - Stack Overflow

jquery ajax file-upload multipartform-data form-data
Rectangle 27 37

Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
</form>
$_FILES
Array
(
    [media] => Array
        (
            [name] => Array
                (
                    [0] => Galata_Tower.jpg
                    [1] => 518f.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpIQaOYo
                    [1] => /tmp/phpJQaOYo
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 258004
                    [1] => 127884
                )

        )

)

If you do progressive enhancement, using Raphael's JS to submit the files...

var data = new FormData($('input[name^="media"]'));     
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
    data.append(i, file);
});

$.ajax({
    type: ppiFormMethod,
    data: data,
    url: ppiFormActionURL,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
        alert(data);
    }
});

... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:

Array
(
    [0] => Array
        (
            [name] => Galata_Tower.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpAQaOYo
            [error] => 0
            [size] => 258004
        )

    [1] => Array
        (
            [name] => 518f.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpBQaOYo
            [error] => 0
            [size] => 127884
        )

)

That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:

// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );

// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
    data.append(fileInputName+'['+i+']', file);
});

(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)

  • Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
  • The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.

With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.

Sending multipart/formdata with jQuery.ajax - Stack Overflow

jquery ajax file-upload multipartform-data form-data
Rectangle 27 4

What the problem in ajax is that $_FILES details are not sent in asynchroous request. When we submit the filled form without ajax request and debug in backend side in PHP by

echo '<pre>';
print_r($_FILES); 
print_r($_POST); 
echo '</pre>';
die;

then we successfuly get $_FILES and $_POST data.

But when we debug the same thing in ajax request, we get only $_POST values and we get $_FILES as NULL. This led us to conclusion that $_FILES data are not sent in ajax request by our above code.

FormData

In simple words, it adds all necessary information of file which needs to be uploaded to data param in $.ajax OR fill up $_FILES as well as all $_POST data ie non file input such as strings number etc.

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>    
<button type="button" class="btn btn-success subm">Upload</button>
<?php ActiveForm::end(); ?>

<script>
$('.subm').click(function(e){
    var formData = new FormData($('form')[0]);
    console.log(formData);
    $.ajax({
        url: "some_php_file.php",  //Server script to process data
        type: 'POST',

        // Form data
        data: formData,

        beforeSend: beforeSendHandler, // its a function which you have to define

        success: function(response) {
            console.log(response);
        },

        error: function(){
            alert('ERROR at PHP side!!');
        },


        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});
</script>

Now make ajax request and debug in PHP code by print_r() as shown above, you will notice that $_FILES is not NULL and its contains all file (which needs to be uploaded) data. And if it is set you can upload using move_uploaded_file() funtion

So this is how you file is uploaded via Ajax.

cache
contentType
processData

php - Upload Ajax file in yii2 - Stack Overflow

php ajax yii2
Rectangle 27 0

AJAX doesn't do file uploads. It's not designed for that. The standard workaround is to have the JS code build a hidden iframe and do a standard POST-type upload in that. As such, if you try doing echo $_FILES['q']['error'], you'd probably have gotten 4 for "no file".

I've tried with $_FILES['q']['error'] but still without any response from the server... My problem is that I would like to implement drag and drop to upload a file, isn't it possible anyhow? I actually don't really need Ajax, but for what I've seen around the only option seemed to be Ajax, but then if you say so I'm a bit confused...

This answer may have been valid at the time of posting but may not be completely correct today

javascript - PHP and Ajax file upload - Can't get the tmp_name with $_...

php javascript ajax file-upload
Rectangle 27 0

Check out this answer for making file uploads with AJAX. It is possible, but not compatible in all browsers.

Alternatively, if you want on the fly uploads, there is a cool library you can get called 'Uploadify'. It's a flash/jquery (or HTML5 now) rig that allows you to upload files on the fly. In the flash version, last time I used it... you can add in callback functions to make it do essentially anything you want.

Perfect thank's! I've looked at the other question and realized how to use formData. It has solved the problem, now it gets the file with Ajax as I was trying to do.

javascript - PHP and Ajax file upload - Can't get the tmp_name with $_...

php javascript ajax file-upload
Rectangle 27 0

He wants to show the progress of a file he uploads. It works via JavaScript and iFrame, but when I tried, I wasn't able to get ASP.NET to do the same as PHP, probably because ASP.NET is doing it synchronously by default, while PHP is async.

If that's indeed what you want, I reccommend JQuery uploadify.

You find more info on JQuery Uploadify with WebForms in my post here: Multiple fileuploads with ASP.NET MVC

asp.net - ASP File Is Working, but - Stack Overflow

asp.net asp.net-ajax
Rectangle 27 0

AJAX doesn't do file uploads. It's not designed for that. The standard workaround is to have the JS code build a hidden iframe and do a standard POST-type upload in that. As such, if you try doing echo $_FILES['q']['error'], you'd probably have gotten 4 for "no file".

I've tried with $_FILES['q']['error'] but still without any response from the server... My problem is that I would like to implement drag and drop to upload a file, isn't it possible anyhow? I actually don't really need Ajax, but for what I've seen around the only option seemed to be Ajax, but then if you say so I'm a bit confused...

This answer may have been valid at the time of posting but may not be completely correct today

javascript - PHP and Ajax file upload - Can't get the tmp_name with $_...

php javascript ajax file-upload
Rectangle 27 0

I'll start off by saying that I haven't been able to generate a working copy and most of this is my understanding from reading around and slight expirience. That said, perhaps you could explore it a bit more and/or set me straight if I'm wrong. The main thing points to the idea of the classic form with a hidden input named MAX_FILE_SIZE... In PHP/Apache, the server will stop if the upload is larger than the MAX_FILE_SIZE (see last post from here). On the PHP side of things, the $_FILES array will return an error code (which can be seen here). Take note of UPLOAD_ERR_FORM_SIZE. To put this all together, you could have JavaScript upload the file within an IFrame and get the result. If the server spits out an error message (which, in this theory, would be quite quickly), JavaScript can simply alert the user. Otherwise, we can assume the file is now uploaded successfully. Now trying to make sense of Google's code is near impossible; a quick HTML scan is as far as I go and it didn't help any... They do indeed have hidden input fields but none with MAX_FILE_SIZE as the name. They are much shorter and most don't appear to have values. But, I believe this could be possible. Thoughts anyone? Who knows, perhaps the great Google Web Server is built in with the power to cut off uploads instantly. Thanks for listening!

c# - Recommended way to check file size on upload - Stack Overflow

c# http file-upload website http-headers
Rectangle 27 0

Check out this answer for making file uploads with AJAX. It is possible, but not compatible in all browsers.

Alternatively, if you want on the fly uploads, there is a cool library you can get called 'Uploadify'. It's a flash/jquery (or HTML5 now) rig that allows you to upload files on the fly. In the flash version, last time I used it... you can add in callback functions to make it do essentially anything you want.

Perfect thank's! I've looked at the other question and realized how to use formData. It has solved the problem, now it gets the file with Ajax as I was trying to do.

javascript - PHP and Ajax file upload - Can't get the tmp_name with $_...

php javascript ajax file-upload
Rectangle 27 0

AJAX doesn't do file uploads. It's not designed for that. The standard workaround is to have the JS code build a hidden iframe and do a standard POST-type upload in that. As such, if you try doing echo $_FILES['q']['error'], you'd probably have gotten 4 for "no file".

I've tried with $_FILES['q']['error'] but still without any response from the server... My problem is that I would like to implement drag and drop to upload a file, isn't it possible anyhow? I actually don't really need Ajax, but for what I've seen around the only option seemed to be Ajax, but then if you say so I'm a bit confused...

javascript - PHP and Ajax file upload - Can't get the tmp_name with $_...

php javascript ajax file-upload
Rectangle 27 0

Check out this answer for making file uploads with AJAX. It is possible, but not compatible in all browsers.

Alternatively, if you want on the fly uploads, there is a cool library you can get called 'Uploadify'. It's a flash/jquery (or HTML5 now) rig that allows you to upload files on the fly. In the flash version, last time I used it... you can add in callback functions to make it do essentially anything you want.

Perfect thank's! I've looked at the other question and realized how to use formData. It has solved the problem, now it gets the file with Ajax as I was trying to do.

javascript - PHP and Ajax file upload - Can't get the tmp_name with $_...

php javascript ajax file-upload
Rectangle 27 0

I have used the code from this link "http://www.formget.com/ajax-image-upload-php/" to get what you needed. This code apart from saving the file into a folder will save it into a database. I have made a folder images to store image files and two php files one which shows frontend html form with javascript code and the other for upload and display. The HTML code "index.php" is this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
<input type="hidden" name="image_id" id="image_id" value="2" class="submit" />
</div>
</form>
</div>
<h4 id='loading' >loading..</h4>
<div id="message"></div>

<style>
.userimg {
	width: 50px;
	height:auto;
	
}
</style>

<script type="text/javascript">

  $(document).ready(function (e) {
		$("#uploadimage").on('submit',(function(e) {
		e.preventDefault();
	    $("#message").empty();
		$('#loading').show();
		$.ajax({
		url: "upload.php", // Url to which the request is send
		type: "POST",             // Type of request to be send, called as method
		data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
		contentType: false,       // The content type used when sending data to the server.
		cache: false,             // To unable request pages to be cached
		processData:false,        // To send DOMDocument or non processed data file it is set to false
		success: function(data)   // A function to be called if request succeeds
		{
		$('#loading').hide();
		$("#message").html(data);
		}
		});
		}));
		
		// Function to preview image after validation
		$(function() {
		$("#file").change(function() {
		$("#message").empty(); // To remove the previous error message
		var file = this.files[0];
		var imagefile = file.type;
		var match= ["image/jpeg","image/png","image/jpg"];
		if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
		{
		$('#previewing').attr('src','noimage.png');
		$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
		return false;
		}
		else
		{
		var reader = new FileReader();
		reader.onload = imageIsLoaded;
		reader.readAsDataURL(this.files[0]);
		}
		});
		});
		function imageIsLoaded(e) {
		$("#file").css("color","green");
		$('#image_preview').css("display", "block");
		$('#previewing').attr('src', e.target.result);
		$('#previewing').attr('width', '250px');
		$('#previewing').attr('height', '230px');
		};
});

</script>
<style>
body {
font-family: 'Roboto Condensed', sans-serif;
}
h1
{
text-align: center;
background-color: #FEFFED;
height: 70px;
color: rgb(95, 89, 89);
margin: 0 0 -29px 0;
padding-top: 14px;
border-radius: 10px 10px 0 0;
font-size: 35px;
}
.main {
position: absolute;
top: 50px;
left: 20%;
width: 450px;
height:530px;
border: 2px solid gray;
border-radius: 10px;
}
.main label{
color: rgba(0, 0, 0, 0.71);
margin-left: 60px;
}
#image_preview{
position: absolute;
font-size: 30px;
top: 100px;
left: 100px;
width: 250px;
height: 230px;
text-align: center;
line-height: 180px;
font-weight: bold;
color: #C0C0C0;
background-color: #FFFFFF;
overflow: auto;
}
#selectImage{
padding: 19px 21px 14px 15px;
position: absolute;
bottom: 0px;
width: 414px;
background-color: #FEFFED;
border-radius: 10px;
}
.submit{
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 300px;
border-radius: 5px;
padding: 10px 0;
outline: none;
margin-top: 20px;
margin-left: 15%;
}
.submit:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
#file {
color: red;
padding: 5px;
border: 5px solid #8BF1B0;
background-color: #8BF1B0;
margin-top: 10px;
border-radius: 5px;
box-shadow: 0 0 15px #626F7E;
margin-left: 15%;
width: 72%;
}
#message{
position:absolute;
top:120px;
left:815px;
}
#success
{
color:green;
}
#invalid
{
color:red;
}
#line
{
margin-top: 274px;
}
#error
{
color:red;
}
#error_message
{
color:blue;
}
#loading
{
display:none;
position:absolute;
top:50px;
left:850px;
font-size:25px;
}
</style>

For the upload script and display after upload (upload.php) you can use

<?php

if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$maxsize = 99999999;
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < $maxsize)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("images/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/".$_FILES['file']['name']; // Target path where file is to be stored

 $size = getimagesize($_FILES['file']['tmp_name']);
 /*** assign our variables ***/
 $type = $size['mime'];
 $imgfp = fopen($_FILES['file']['tmp_name'], 'rb');
 $size = $size[3];
 $name = $_FILES['file']['name'];



 /*** check the file is less than the maximum file size ***/
 if($_FILES['file']['size'] < $maxsize )
 {
 /*** connect to db ***/
 $dbh = new PDO("mysql:host=localhost;dbname=DM_NAME", 'DB_USER', 'DB_PASSWORD');

 /*** set the error mode ***/
 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 /*** our sql query ***/
 $stmt = $dbh->prepare("INSERT INTO imageblob (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");

 /*** bind the params ***/
 $stmt->bindParam(1, $type);
 $stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
 $stmt->bindParam(3, $size);
 $stmt->bindParam(4, $name);

 /*** execute the query ***/
 $stmt->execute();
 $lastid = $dbh->lastInsertId(); 
 //Move uploaded File
 move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
 if(isset($lastid))
 {
 /*** assign the image id ***/
 $image_id = $lastid;
	 try {
	 /*** connect to the database ***/
	 /*** set the PDO error mode to exception ***/
	 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	
	 /*** The sql statement ***/
	 $sql = "SELECT image, image_type FROM imageblob WHERE image_id=$image_id";
	
	 /*** prepare the sql ***/
	 $stmt = $dbh->prepare($sql);
	
	 /*** exceute the query ***/
	 $stmt->execute(); 
	
	 /*** set the fetch mode to associative array ***/
	 $stmt->setFetchMode(PDO::FETCH_ASSOC);
	
	 /*** set the header for the image ***/
	 $array = $stmt->fetch();
	 /*** check we have a single image and type ***/
	 if(sizeof($array) == 2)
	 {
		 //To Display Image File from Database
		 echo '<img src="data:image/jpeg;base64,'.base64_encode( $array['image'] ).'"/>';

	 }
	 else
	 {
	 throw new Exception("Out of bounds Error");
	 }
	 }
	 catch(PDOException $e)
	 {
	 echo $e->getMessage();
	 }
	 catch(Exception $e)
	 {
	 echo $e->getMessage();
	 }
	 }
	 else
	 {
	 echo 'Please input correct Image ID';
	 }
 }
 else
 {
 /*** throw an exception is image is not of type ***/
 throw new Exception("File Size Error");
 }
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>

You can download the entire code from here http://www.filehosting.org/file/details/569640/upload.zip. Change the database details and also image displayed is the last insert id in the form . I hope you can do the rest.

Thank you. I downloaded the full code to try it out before implementing but am running into errors - I filled in my database details (line 39) and am running the entire folder locally to test it but am getting an error with execute() saying "Base table or view not found." I edited my question above - what am I doing wrong here? Do I need to change something else?

Its a simple error which says it is unable to find the table. In the code the table used is imageblob. Just replace it with your table name. Find this line in upload.php and replace it $stmt = $dbh->prepare("INSERT INTO imageblob. You have to replace table name at two places.

Right, I tried that originally by replacing image blob with my column name (img) but received the same error. I then changed that my table name (accounts) but received the error "Column not found: 1054 Unknown column 'image_type' in 'field list." Really need help understanding this - I've included screenshots my phpadmin and errors

Dont change the table name and run the sql script provided in the script. It will create table with appropriate columns.

Follow this steps to create another table. Click on Database sqlserver. Click Sql -> Paste the sql code and run it. Later you can connect these two tables using user id. Or in table accounts create the 5 missing columns manually.

php - upload image from submit form to mysql database and display imag...

php html mysql image