Can I pass image form data to PHP function for upload?

I am trying to use jquery and PHP to load an image like this:

Html

<form id="form-photo" enctype="multipart/form-data"><
  <span class="btn btn-small fileinput-button">
    <span>Add Photo</span>
    <input type="file" name="photo-img" id="photo-img">
  </span>
</form>

      

The current jquery structure looks like this:

$('#photo-img').change(function(){
    var file = this.files[0];

    //console.log(file);
    name = file.name;
    size = file.size;
    type = file.type;

    // I'll do some validation here before proceeding

    var formData = new FormData($('#form-photo'));

    console.log(formData);

   // How do I pass the image form data to a PHP function via jquery?

});

      

Is it possible to simply pass formData to a PHP function via jquery post?

+2


source to share


3 answers


Tested and works on Goolge Chrome

, Opera

, Firefox

, Safari

.
doesn't work with IE8 or lower

Javascript

Create an object FormData

and add file

with index photo-img

and POST

to your server withXMLHttpRequest

$(function() {
  $('#photo-img').change(function(){
    var file  = this.files[0];

    // do your validation here

    var formData  = new FormData();
    formData.append( 'photo-img', file ); // append the file to form data

    var xhr = false;
    if ( typeof XMLHttpRequest !== 'undefined' ) {
      xhr = new XMLHttpRequest();
    }
    else {
      var versions  = [ "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ];
      for( var i = 0, len = versions.length; i < len; i++ ) {
        try {
          xhr = new ActiveXObject( versions[i] );
          break;
        }
        catch(e) {}
      }
    }
    if ( xhr ) {
      // replace test.php with your own upload script url
      xhr.open( "POST", "test.php", true );
      xhr.onreadystatechange  = function() {
        if ( this.readyState === 4 && this.status == 200 ) {
          var response  = this.response || this.responseText;

          /** Do Something with the reponse **/
          response  = $.parseJSON( response );
          if ( response && response.message ) {
            window.alert( response.message );
          }

        }
      }
      // now send the formData to server
      xhr.send( formData );
    }
  });
});

      



PHP

Better server side image loading handling and returning an object JSON

as a response

<?php
  if ( isset( $_FILES["photo-img"] ) ) {
    $error  = false;
    $image  = $_FILES["photo-img"];
    $code   = (int)$image["error"];
    $valid  = array( IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF );
    $folder = dirname( __FILE__ )."/upload/"; // path to folder to where you want to move uploaded file
    $target = $folder.$image["name"];

    if ( !file_exists( $folder ) ) {
      @mkdir( $folder, 0755, true ) ;
    }

    if ( $code !== UPLOAD_ERR_OK ) {
      switch( $code ) {
        case UPLOAD_ERR_INI_SIZE:
          $error  = 'Error '.$code.': The uploaded file exceeds the <a href="http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize" target="_blank" rel="nofollow"><span class="function-string">upload_max_filesize</span></a> directive in php.ini';
        break;
        case UPLOAD_ERR_FORM_SIZE:
          $error  = 'Error '.$code.': The uploaded file exceeds the <span class="const-string">MAX_FILE_SIZE</span> directive that was specified in the HTML form';
        break;
        case UPLOAD_ERR_PARTIAL:
          $error  = 'Error '.$code.': The uploaded file was only partially uploaded';
        break;
        case UPLOAD_ERR_NO_FILE:
          $error  = 'Error '.$code.': No file was uploaded';
        break;
        case UPLOAD_ERR_NO_TMP_DIR:
          $error  = 'Error '.$code.': Missing a temporary folder';
        break;
        case UPLOAD_ERR_CANT_WRITE:
          $error  = 'Error '.$code.': Failed to write file to disk';
        break;
        case UPLOAD_ERR_EXTENSION:
          $error  = 'Error '.$code.': A PHP extension stopped the file upload';
        break;
        default:
          $error  = 'Error '.$code.': Unknown upload error'; 
        break; 
      }
    }
    else {
      $iminfo = @getimagesize( $image["tmp_name"] );
      if ( $iminfo && is_array( $iminfo ) ) {
        if ( isset( $iminfo[2] ) && in_array( $iminfo[2], $valid ) && is_readable( $image["tmp_name"] ) ) {
          if ( !move_uploaded_file( $image["tmp_name"], $target ) ) {
            $error  = "Error while moving uploaded file";
          }
        }
        else {
          $error  = "Invalid format or image is not readable";
        }
      }
      else {
        $error  = "Only image files are allowed (jpg, gif, png)";
      }
    }
    if ( empty( $error ) ) {
      echo json_encode( array( "error" => 0, "message" => "Upload success!" ) );
    }
    else {
      echo json_encode( array( "error" => 1, "message" => $error ) );
    }
    exit();
  }
?>

      

+4


source


You can use $ .ajax method in jquery and submit form data to php file.



 $.ajax({
  type: "POST",
  url: "http://localhost/index.php",
  data: data,
  success: success,
});

      

+2


source


Note that $ .post and $ .ajax are very similar (except for $ .ajax uses type = get, you must change it to type = post). You have more control over your files with $ .ajax, but $ .post is more streaming - think of $ .post as a shortcut way to do AJAX POST. However, since $ .ajax is often more structured than $ .post, this is a great way for anyone new to AJAX to experiment with adding modifiers like dataType:JSON

, contentType

or even async:false

.

The Ajax code would like:

$('#photo-img').change(function(){
    var file = this.files[0];

    //console.log(file);
    name = file.name;
    size = file.size;
    type = file.type;

    $.ajax({
        type: "POST",
        url: "your_php_file.php",
        data: 'f_name=' +name+ '&f_size=' +size+ '&f_type=' +type,
        success: function(whatigot) {
            alert('Server-side response: ' + whatigot);
        } //END success fn
    }); //END $.ajax
}); //END dropdown change event

      


Please note that any data returned from the PHP file goes into your HTML document in the success function of the AJAX call and must be processed there . This way when you insert the received data into the DOM.

For example, let's say your HTML document has a DIV with id="myDiv"

. To insert data from PHP into an HTML document, replace the line: with the alert('Server-side response: ' + whatigot);

following:

$('#myDiv').html(whatIgot);

      

Your DIV now contains data fetched from a PHP file.


On the PHP side, it looks like this:

<?php
    $file_name = $_POST['f_name'];
    $file_size = $_POST['f_size'];
    $file_type = $_POST['f_type'];

    //Here is where you do some stuff, such as MySQL lookups, etc
    //Then build the response to send back (default is HTML, unless 
    //you specify something else like JSON)

    $r = 'The PHP File received:<br><br>';
    $r .= '
        <ul>
            <li>File Name: ' .$file_name.'</li>
            <li>File Size: ' .$file_size.'</li>
            <li>File Type: ' .$file_type.'</li>
        </ul>
    ';
    echo $r;

      


See this example for ideas on how this works.

Note that the examples above are using jQuery and therefore require this link in your page tags:

<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

      

+1


source







All Articles