【问题标题】:Can I pass image form data to a PHP function for upload?我可以将图像表单数据传递给 PHP 函数进行上传吗?
【发布时间】:2013-06-26 18:20:04
【问题描述】:

我正在尝试使用 jquery 和 PHP 来上传这样的图像:

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>

当前的 jquery 框架如下所示:

$('#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?

});

我可以通过 jquery post 将 formData 传递给 PHP 函数吗?

【问题讨论】:

标签: php jquery ajax


【解决方案1】:

已在 Goolge ChromeOperaFirefoxSafari 上测试和工作。
doesn't work with IE8 or lower

Javascript

创建一个FormData 对象并在XMLHttpRequest 的帮助下将带有索引photo-imgPOSTfile 附加到您的服务器

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

在服务器端更好地处理图像上传并返回JSON 对象作为响应

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

【讨论】:

  • 清洁解决方案。很好的验证。
【解决方案2】:

您可以在 jquery 中使用 $.ajax 方法并将表单数据发送到 php 文件。

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

【讨论】:

    【解决方案3】:

    请注意,$.post 和 $.ajax 非常相似(除了默认情况下 $.ajax 使用 type=get,您必须将其更改为 type=post)。使用 $.ajax 可以更好地控制内容,但 $.post 更加流畅——将 $.post 视为执行 AJAX POST 的快捷方式。但是,由于 $.ajax 通常比 $.post 更结构化,因此对于 AJAX 新手来说,这是尝试添加修饰符的好方法,例如 dataType:JSONcontentType,甚至是 async:false

    Ajax 代码是这样的:

    $('#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
    

    请注意,从 PHP 文件返回的任何数据都会在AJAX 调用的成功函数 中进入您的HTML 文档,并且必须在那里 处理。这就是您将接收到的数据插入 DOM 的地方。

    例如,假设您的 HTML 文档有一个带有 id="myDiv" 的 DIV。要将 PHP 中的数据插入 HTML 文档,请将行:alert('Server-side response: ' + whatigot); 替换为:

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

    您的 DIV 现在包含从 PHP 文件回显的数据。


    在 PHP 方面,它基本上是这样的:

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

    请参阅 this example 了解其工作原理。

    请注意,以上示例使用 jQuery,因此需要在页面的标签中引用此引用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多