使用AJAX POST / GET方法解析Base64字符串时未定义的索引

时间:2019-01-16 23:28:29

标签: javascript php jquery

我正在尝试将图像从我的cordova应用程序上传到我的服务器(PHP将接收base64数据解码并保存它),但是我在POST中遇到错误,即PHP端的未定义索引,我无法确定找出导致错误的原因。我尝试在PHP中分配base64字符串,但仍然收到错误消息,指出它未定义。

我尝试在PHP文件中使用$ _GET,但仍然无法使用

// https://www.npmjs.com/package/cordova-plugin-camera
var a;
var app = {
    image: null,
    imgOptions:null,


    initialize: function() {
      // Use deviceready on a device in in the emulator
           //     document.addEventListener('deviceready', this.onDeviceReady, false);
      // Use DOMContentLoaded in a browser
        document.addEventListener("DOMContentLoaded", this.onDeviceReady, false);
    },

    onDeviceReady: function() {
        document.querySelector("#btn").addEventListener("click", app.callCamera);
        console.log("button listener added");
        app.image = document.querySelector("#image");
        document.querySelector('#testtestx').addEventListener("click",app.UploadtoServer);
    },


    callCamera: function () {
        app.imgOptions = {quality : 100,
                destinationType: Camera.DestinationType.DATA_URL,
                sourceType: Camera.PictureSourceType.CAMERA,
                allowEdit : false,
                encodingType : Camera.EncodingType.JPEG,
                mediaType: Camera.MediaType.PICTURE,
                targetWidth : 200,
                cameraDirection : Camera.Direction.FRONT,
                saveToPhotoAlbum : false
               };

        navigator.camera.getPicture( app.imgSuccess, app.imgFail, app.imgOptions );
    },
    //OnSuccess Function
    imgSuccess: function (imageData) {
         a = "data:image/jpeg;base64," + imageData;
         localStorage.setItem('base64imgimg',a);
        //got an image back from the camera
        app.image.src = "data:image/jpeg;base64," + imageData;
        //console.log("Image loaded into interface");
        //clear memory in app
        navigator.camera.cleanup();
    },


    //OnFail Function
    imgFail: function (msg) {
        console.log("Failed to get image: " +  msg);
    },


    UploadtoServer: function (e) {
        e.preventDefault();
        var url = 'MYSERVERURLREPLACEDDUETOSENSITIVEITY';
        var killmeplease = localStorage.getItem('base64imgimg');
        console.log(killmeplease);
        var JSONObject = {
            "image": killmeplease,
            "name": 'test'
        }
        $.ajax({
            url: url, //A string containing the URL to which the request is sent.
            type: 'POST',
            data: JSONObject, //Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
            dataType: 'json', //Evaluates the response as JSON and return a JS object
            contentType: "application/json; charset=utf-8",
            success: function (data) { //function to be called if the request succeeds //this function will be called
              console.log('d');
            },
        });



    }
};

app.initialize();

这是我的PHP代码

<?php


 //$currentdir = (dirname(__FILE__));
 $image = $_POST['image'];
 $name = $_POST['name'];


class image{

private $save_path = 'sdc/images/';
private $image_string = '';
private $image_name = '';
private $image;
private $response = array();

public $loaded = false;

public function __construct(){
    $this->response = array(
        'success' => 0,
        'message' => 'unknown error.'
    );
    $this->image_name = filter_input(INPUT_POST, 'name');
    $this->image_string = filter_input(INPUT_POST, 'image');
    if(!empty($this->image_name) && !empty($this->image_string)){
        $this->loaded = true;
    }
}

我的基本64位字符串。

data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAVgAAABsCAMAAAAYLlp9AAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAMAUExURUxpcf////////////////////////NwIf////////////////NwIf////////////////NwIf////////////////////////////////////////////////////////////////////////////////////////////NwIf////////////////////////////////////////////////////////////////////////////////////////////////////////////////NwIfNwIf////////////////////////////////////////////////////NwIf////////////////////////////////////////////////////////////////////////////////////////////////////NwIf////////////////NwIfNwIfNwIfNwIf////////////////////////////////////////////////////////////////////////////////NwIf////////////////////////////////////////NwIfNwIf////////NwIf////NwIfNwIfNwIfNwIfNwIf////////////////////////////NwIf////////////////NwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIf////////////////////////////////////NwIf////NwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIf////////////////////////////NwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIf////NwIfNwIfNwIfNwIfNwIfNwIfNwIf////NwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwIfNwI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gWbhZyVeW+kpUMbhk/1er2KYPeAzfeuTn8Z3p5rwUTquBuiCAq2seOvQJY7wA5s5q+JN++5S9VmQ+v7NVWIzBCsFFj9mxO43FJSzlUyHUmgHIDzw83P1ODqINidYDU3UPOXIEmtbK9sOffBeiMtJTwljmB3gn10A0Px9SbJp97VkJ/EcFEbA2uKYKXADrzX/k3zJPESxJ+5nQuGl37gXBUEuxesUXICrXfm0vFvSHDtNYL9bEgofEGw+1VBng2rwqX/nt8bAbyOt8GdgpHaPgWzEex/dCxpNTbfXbsLKeEMNgkuP94y0qBub0IbLwQbfeeVAIAWETe4wiFM6TwofMThJX8I09a9LgEa91Roqcup+9kg9gJeGsFKgCUWJP+YxYSSONmo0Hw9+Ur44fZi3KlntR77uDDaIFgJsEp/4RSoBf5TCZC/bD1gXf2LYGXAKnrv0K+qDcTMV8tP2GPCFASClQCrKOfm9XJI7fKRRkIfxucT6x7kwcpkY6w+mYBi+AdEBV3Rb3VaVQAAAABJRU5ErkJggg==

1 个答案:

答案 0 :(得分:0)

啊。您不是在进行表单或多部分编码的POST,而只是将原始JSON填充到POST正文中。 PHP不会对此进行解码,因此不会在$_POST中填充任何内容。

原始POST正文将在特殊流php://input中可用,您可以像这样捕获和解码它:

$rawPost = file_get_contents('php://input');
$decodedPost = json_decode($rawPost);
$image = $decodedPost->image;

如果您想让PHP本地处理请求解析,您将想知道如何使JavaScript进行正确的multipart/form-data POST。另外,您可以按原样上传映像,而无需对其进行base64设置,这样可以节省25%的请求大小,PHP会将其写入临时文件而不是内存中。