php - 使用 Kendo Upload 的 Kendo Grid 内联编辑返回空结果

标签 php jquery kendo-ui kendo-grid kendo-upload

我有 Kendo UI Grid 和 inline 编辑和我的字段之一 (propertyLogo) 我使用 kendoUpload上传图像。使用 kendoUpload 函数 fileUploadEditor,我使用 saveUrl: "./image.php", 并将图像转换为 base64 格式以保存到数据库中.当我添加/编辑时,我设法成功更新所有字段,但 propertyLogo 字段除外,它返回 NULL 结果。我不知道我做错了哪一部分,但我无法将图像保存到数据库中。在这里,我将提供我的脚本。

enter image description here

我的数据源和网格

/****************/
/** DATASOURCE **/
/****************/
  
  var dataSource = new kendo.data.DataSource({
    transport: {
      read: {
        url:  "./getPropertyMasterData.php",
        type: "POST",
        data: function() {
          return { 
            method: "getPropertyMasterData",
          }
        }
      },
     
      update: {
        url:  "./getPropertyMasterData.php",
        type: "POST",
        data: function () {
          console.log("I'm calling update!!");
          return {
            method: "editPropertyMasterData",
          }
        },	
        complete: function (e) {  
          $('#grid').data('kendoGrid').dataSource.read();
        } 
      },
      
      destroy: {
        url:  "./getPropertyMasterData.php",
        type: "POST",
        data: function () {
          return {
            method: "deletePropertyMasterData",
          }
        },
        complete: function (e) {  
          $('#grid').data('kendoGrid').dataSource.read();
        } 
      },
    },
    schema: {
      model: {
        id: "propertyID",
        fields: {
          propertyID: { editable: false, nullable: true }
          active: { editable: false, nullable: false, defaultValue: 'y'},
          propertyName: { editable: true,type: "string",validation: {required: {message: "Required"}} },
          propertyLogo: { editable: true, type: "string",validation: {required: {message: "Required"}} },
          propertyColor: { defaultValue: "#000", editable: true, validation: { required: {message: "Required"}} },
          businessRegistrationNo: { editable: true,type: "string",validation: {required: {message: "Required"}} },
          noOfRooms: { defaultValue: 1, editable: true,type: "number",validation: {min: 1, required: {message: "Required"}} }

        }
      }
    },
    pageSize: 25
  }); // End of Kendo DataSource
  
  
/****************/
/** KENDO GRID **/
/****************/
  
  var grid = $("#grid").kendoGrid({
  dataSource: dataSource,
  sortable: true,
  editable: {	mode: "inline" },
  columns: [ 
    { field: "active", title:" ", filterable: false,
       template: "# if (active=='y'){# <span class='k-icon ehors-status-active-icon'></span> #} else {# <span class='k-icon ehors-status-inactive-icon'></span> # }#"}, 

    { field: "propertyName", title:"Property Name",  width: "80" },

    { field: "businessRegistrationNo", title:"Business Reg. No.",  width: "80" },

    { field: "propertyLogo", title:"Logo",  width: "80", editor: fileUploadEditor
    ,template: "<div class='propertyLogo'><a></a>#=propertyLogo#</div>" },

    { field: "propertyColor", title:"Color", width: "80px",  editor : getColor, template:  function(dataItem) {
      return "<div style='background-color: " + dataItem.propertyColor + ";'>&nbsp;</div>";
    }},

    { field: "noOfRooms", title:"No of Rooms",  width: "80px", format: "", template: "<div class='unit'>#= noOfRooms#</div>" },

    //Button Name
    { command: [{ name: "edit", text: {	
      edit: "Edit", 
      update: "Update", 
      cancel: "Cancel"} } 
      ], title: "" }
  ],
  save: onSave, // <--  checking duplicate error.
  noRecords: {template: "No Records" }	
}).data("kendoGrid");  //end of kendo grid


function fileUploadEditor(container, options) {
  $('<input type="file" id="fileUpload" name="fileUpload" /> ')
  .appendTo(container)
  .kendoUpload({ 
    multiple:false,
    async: {
      saveUrl: "./image.php",
      autoUpload: true,
    },
    validation: {
      allowedExtensions: [".jpg", ".png", ".jpeg"]
    },
    success: onSuccess,    // just a console log to view progress
    upload: onUpload,      // just a console log to view progress
    progress: onProgress   // just a console log to view progress
  });
}

我的 image.php

图像将转换为base64 并存储到hexString 变量中。一旦 getPropertyMasterData.php 被调用,它将获取 hexString 值。目前在这里我可以看到它成功返回了一个值。

<?php  
$file = $_FILES['fileUpload'];	
$fileName = $_FILES['fileUpload']['name'];
$fileTmpName = $_FILES['fileUpload']['tmp_name']; //directory location	
$fileSize = $_FILES['fileUpload']['size'];
$fileError = $_FILES['fileUpload']['error'];  //default 0 | 1 got error

$fileExt = explode('.', $fileName);	  //split file name to get ext name.
$fileActualExt = strtolower(end($fileExt)); //change to lowercase for the extension file
$allowed = array('jpg','jpeg','png');

  if (!in_array($fileActualExt, $allowed)) {
    return ['error' => 'You cannot upload files of this type!'];
  }

  if ($fileError !== 0) {
    return ['error' => 'Error occur when upload file!'];
  }

  if ($fileSize > 500000) {
    return ['error' => 'Your file size is too big!'];
  }

$fileDestination = './uploads/' . $fileName;                    
move_uploaded_file($fileTmpName, $fileDestination); 

$data = file_get_contents($fileTmpName);
return ['hexString' => base64_encode($data)];
?>

我的 getPropertyMasterData.php
据说 $uploadPayload['hexString'] 将从 image.php 中获取一个变量,但不知何故它会返回 NULL 结果。其他领域工作正常。

<?php
  $propertyID = "1";
  include($_SERVER['DOCUMENT_ROOT'] . '/TM.pdo.php'); 
  $ehorsObj = new TM();
  $ehorsObj->TM_CONNECT($propertyID);

  $uploadPayload = require "image.php";  // READ FILE FROM image.php  |  Return NULL result

  if (isset($uploadPayload['error'])) {
      // echo $uploadPayload['error']);
      /* do something in case of error */
  }

  $method = $_POST['method'];
  switch ($method){
    case "getPropertyMasterData" :
      $method($ehorsObj);
      break;

    case "editPropertyMasterData" :
      $method($ehorsObj, $uploadPayload['hexString']);
      break;
    default:
      break;
  }


  /** READ **/  
  function getPropertyMasterData($ehorsObj) {
      $getcheckbox = (isset($_POST['c1']) ? $_POST['c1'] : "all"); // by default select *
      $sql         = "SELECT * FROM tblAdmProperty ";
      if ($getcheckbox == "true") {
        $sql .= " WHERE active = 'y' ";
    } 
    $sql .= " ORDER BY 2 ASC " ;
    $array = array();	

    $GetResult = $ehorsObj->FetchData($sql, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
    while ($row = $GetResult->fetch()){
      $array[] = $row;
    }
    header("Content-type: application/json");
    $result = json_encode($array);
    echo $result;
  }


  /** EDIT **/
  function editPropertyMasterData($ehorsObj, $NewHexString) {
    $propertyID     = (isset($_POST['propertyID']) ? $_POST['propertyID'] : '');
    $propertyName   = (isset($_POST['propertyName']) ? $_POST['propertyName'] : '');
    $propertyLogo   = (isset($_POST['propertyLogo']) ? $_POST['propertyLogo'] : '');
    $propertyColor   = (isset($_POST['propertyColor']) ? $_POST['propertyColor'] : '');
    $businessRegistrationNo   = (isset($_POST['businessRegistrationNo']) ? $_POST['businessRegistrationNo'] : '');
    $noOfRooms   = (isset($_POST['noOfRooms']) ? $_POST['noOfRooms'] : '');
    $active 		= (isset($_POST['active']) ? $_POST['active'] : '');

    $sqlUpdate = " UPDATE tblAdmProperty
      SET propertyName = '" . $propertyName . "',
      propertyLogo = '" . $NewHexString . "',
      propertyColor = '" . $propertyColor . "',
      businessRegistrationNo = '" . $businessRegistrationNo . "',
      noOfRooms = '" . $noOfRooms . "',
      active = '" . $active . "'
      WHERE propertyID = '" . $propertyID . "' ";  
    $ehorsObj->ExecuteData($sqlUpdate, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
  }

?>

如果我使用 cookie 或 session ,它会起作用,但我尽量避免使用它们。我希望我能提供一个明确的解释。

最佳答案

最后,我设法让它发挥作用。

  1. 首先,我创建一个隐藏的文本框 <input type="hidden" id='uploadedFile' data-bind="value: propertyLogo" />

  2. 修复了我的 fileUploadEditor功能并添加remove.php (选修的)。 onSucces事件将在 image.php 中获取服务器响应并插入我之前创建的文本框值。

function onSuccess(e) {
	console.log(e.response);
	/* push server respoonse to texbox */
	$("#uploadedFile").val(e.response);
}

function fileUploadEditor(container, options){
	$('<input type="file" id="propertyLogo" name="propertyLogo"  /> ')
	.appendTo(container)
	.kendoUpload({
		multiple:false,
		async: {
			saveUrl: "image.php", 
			removeUrl: "remove.php", 
			autoUpload: true,
		},
		validation: {
			allowedExtensions: [".jpg", ".png", ".jpeg"]
	    },
		success: onSuccess
	});
	$("<span class='k-invalid-msg' data-for='propertyLogo'></span>").appendTo(container);
}

  1. image.php 转换为 base64 后, 它需要在 json format

<?php

$fileParam = "propertyLogo";
$uploadRoot = "uploads/";
$files = $_FILES[$fileParam];

  if (isset($files['name'])){
    $error = $files['error'];
    if ($error == UPLOAD_ERR_OK) {

      $fileSize = $files['size'];
      if ($fileSize < 500000) { 		//500000 = 500mb

        $targetPath = $uploadRoot . basename($files["name"]);
        $uploadedFile = $files["tmp_name"];

        /* get a full paths */
        $fullpath = getcwd();
        $newTargetPath = $fullpath . '/' . $targetPath;

        move_uploaded_file($uploadedFile, $newTargetPath); 

        /* convert data into base64 */
        $data = file_get_contents($uploadedFile);
        $hex_string = base64_encode($data);

        header('Content-Type: application/json');
        echo json_encode($hex_string);

      } else {
       echo "Your file size is too big! ";
      }	
    } else {
     echo "Error code " . $error;
    }
  }

  // Return an empty string to signify success
  echo "";

?>

  1. remove.php

<?php
  $fileParam = "propertyLogo";
  $uploadRoot = "uploads/";
  $targetPath = $uploadRoot . basename($_POST["name"]);

  unlink($targetPath);

  echo "";
?>

  1. 最后在我的 Kendo ui Grid 上 save事件我添加这一行,基本上从文本框中获取值并设置到我的 propertyLogo领域

save: function(e){ e.model.set("propertyLogo",$("#uploadedFile").val()); }

关于php - 使用 Kendo Upload 的 Kendo Grid 内联编辑返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56829239/

相关文章:

php - 在 PHP 中有命名变量的首选方法吗?

javascript - Kendo DateRangePicker 中的动态名称

javascript - JQuery - 选择器仅获取剑道选项卡条中第一个网格的值

php - 大量访问时加载 iframe 内容延迟和低速

php - 在共享主机上隐藏 "vendor"文件夹

php - 寻找一种在不返回的情况下调用函数时停止进程的方法

kendo-ui - 用户停止输入后 Kendo UI MVC 自动完成服务器过滤

jquery - 如何将CSS仅应用于光标所在的元素?

jquery - 按两个条件查找(两个条件都出现)

javascript - 使用 JSDoc 记录 jQuery