我可以通过图像格式的数据的PHP函数上传? [英] Can I pass image form data to a PHP function for upload?

查看:121
本文介绍了我可以通过图像格式的数据的PHP函数上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用jQuery和PHP上传图片,像这样:

I'm trying to use jquery and PHP to upload an image like so:

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框架是这样的:

Current jquery framework 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?

});

我可以只通过jQuery后通过FORMDATA的PHP函数?

Can I just pass the formData to a PHP function via jquery post?

推荐答案

测试和工作在 Goolge的Chrome浏览器歌剧火狐 Safari浏览器
不与IE8或更低的工作

Tested and working on Goolge Chrome, Opera, Firefox, Safari.
doesn't work with IE8 or lower

创建一个 FORMDATA 对象,并追加文件与指数照片IMG POST 到您的服务器 XMLHtt prequest

Create a FormData object and append the file with index photo-img and POST it to your server with the help of XMLHttpRequest

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

这篇关于我可以通过图像格式的数据的PHP函数上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆