简体   繁体   中英

Laravel, ajax base64 image not uploading correctly

I'm using DropzoneJS to upload my images. So what I do is to take the base64URL generated by dropzoneJS, and then try to upload as follows:

$( document ).ready(function() {


  var endpoint= $("#endpoint").val();

  var unit = {
    name: '',
    description: '',
    image: '',
    base64Image: '',
    themes: []
  }

  $("#create-unit-btn").on("click", function() {

    unit.name = $("#create-name").val();
    unit.description = $("#create-description").val();
    unit.base64Image = $('#imageDropzone')[0].dropzone.files[0].dataURL;

    var data = {
      '_token': $('meta[name=csrf-token]').attr('content'),
      'unit': unit
    }
    console.log(data);

    $.ajax({
      type: "POST",
      url: endpoint,
      data: data,
      success: function(result){
        console.log(result);
      }
    });
  });

  function validate() {

  }

});

Then to upload the Image I use the following code:

public function create( Request $request ) {

    $data = [];
    $code = 200;
    try {

        $unit = new Unit();
        $unit->name = request()->input('unit.name');
        $unit->description = request()->input('unit.description');
        $url = ImageHandler::StoreBase64ToFile($request->input('unit.base64Image'));
        $unit->image = $url;
        $unit->save();
        $data['unit'] = $unit;

    } catch ( \Illuminate\Database\QueryException $e ) {
        // There was an error
        $code = Response::HTTP_UNPROCESSABLE_ENTITY;
        $data = [];
        $data['error'] = ErrorResponse::create($code, $e->getMessage());
    } catch( ModelNotFoundException $e ) {
        return response()->json(['error' => 'invalid operation'], 406);
    }
    return response()->json($data, $code);

}

The ImageHandler class does the following:

<?php
namespace App\Libraries;

use Storage;

class ImageHandler {
    /**
     * Store a base64 image into the file system this data has to be
     * sended without any header info like:
     *     data:image/png;base64
     * So the info will look something like iVBORw0....hEUgAAAcQ==
     * @param string $base64Data information
     * @param string $filename the filename if not defined then it generates
     *                         a random name
     * @param string $disk disk location, check Storage documentation of
     *                     laravel, by default is stored on the public folder
     *                     so you'll have to run
     *                         php artisan storage:link
     *                     to make the symbolink links
     * @return string url location of the file
     */
    public static function StoreBase64ToFile($base64Data,
        $filename = null,
        $disk = 'public')
    {
        if (strlen($base64Data) < 10) {
            return null;
        }
        $image = base64_decode($base64Data);
        if ($filename == null) {
            $filename = str_random(16);
            $filename .= '_'.time();
            $filename .= '.png';
        }
        $path = 'images/'.$filename;
        $result = Storage::disk($disk)->put($path, $image, 'public');
        if ($result) {
            $url = Storage::disk($disk)->url($path);
            return $url;
        }
        return null;
    }
}

But when I upload the image, even that the process ends correctly, when I try to open the file from my file browser (finder on MacOs), I can't see the uploaded image. I mean the file it's there but I cant see the content of the image I don't know why is not been uploaded correctly.

It was an error of format when I stored the Image. In order to upload the file without any problem I had to do the following before send the request: unit.base64Image = unit.base64Image.replace("data:image/png;base64,", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM