Laravel,ajax base64图像无法正确上传

时间:2018-03-30 03:00:53

标签: javascript jquery laravel base64 dropzone

我正在使用DropzoneJS上传我的图片。所以我所做的是采用dropzoneJS生成的base64URL,然后尝试按如下方式上传:

$( 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() {

  }

});

然后上传图像我使用以下代码:

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);

}

ImageHandler类执行以下操作:

<?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;
    }
}

但是当我上传图片时,即使过程正确结束,当我尝试从我的文件浏览器(MacOs上的查找器)打开文件时,我看不到上传的图像。我的意思是它在那里的文件,但我无法看到图像的内容 我不知道为什么没有正确上传。

1 个答案:

答案 0 :(得分:0)

存储图像时格式错误。为了上传文件没有任何问题,我必须在发送请求之前执行以下操作:unit.base64Image = unit.base64Image.replace("data:image/png;base64,", "");