File upload URL

134 views Asked by At

I am trying to upload a canvas image to my server using AJAX, the AJAX is working fine, however when I give the server the URL it converts it and adds backslash in at every folder in the URL, and I cant see how. I need it to stop adding these backslashes into the string.

if(isset($_POST['saveCanvas']) && $_POST['saveCanvas'] == "1"){
    $img = $_POST['canvasURL'];
    $img = str_replace('data:image/png;base64','',$img);
    $img = str_replace(' ', '+',$img);
    $data = base64_decode($img);
    $file = "https://example.com/wp-content/plugins/my-plugin/images" . uniqid() . '.png';
    $success = file_put_contents($file, $data);

    $return = [];
    $return['success'] = 1;
    $return['message'] = 'Image Uploaded!  ' . $file;

    echo json_encode($return);
}

This is what I want the output to look like https://example.com/wp-content/plugins/my-plugin/images and this is the current output https:\/\/example.com\/wp-content\/plugins\/my-plugin\/images5f7d97548917d.png

2

There are 2 answers

0
Sami Akkawi On

If I am not mistaken, this happens because you are JSON encoding your return array. Did you try to just returning $file upon success?

0
Natnael Ghirma On

Based on your current issue I would suggest you do this on your php.

if(isset($_POST['saveCanvas']) && $_POST['saveCanvas'] == "1"){
    $img = $_POST['canvasURL'];
    $img = str_replace('data:image/png;base64','',$img);
    $img = str_replace(' ', '+',$img);
    $data = base64_decode($img);
    $file = "https://example.com/wp-content/plugins/my-plugin/images" . uniqid() . '.png';
    echo file_put_contents($file, $data) ? $file : 0;

}

This will check if the file has been uploaded and return a file name or the integer 0.

When the response reaches your ajax, the ajax will check the response.

if its 0, it will be counted as false so you can do.

if(response){
//success code
}else{
//fail code
}

For example

alert(response ? 'Image Uploaded! '+ response : 'Failed to upload');