Laravel:将 Base64 .png文件从控制器保存到公用文件夹

2022-08-30 18:13:16

我通过Ajax将png图像文件发送到base64中的控制器。我已经测试并确定控制器已收到id,但仍然无法将其保存到公用文件夹。

这是我的控制器

public function postTest() {
        $data = Input::all();

        //get the base-64 from data
        $base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);

        //decode base64 string
        $image = base64_decode($base64_str);
        $png_url = "product-".time().".png";
        $path = public_path('img/designs/' . $png_url);

        Image::make($image->getRealPath())->save($path);
        // I've tried using 
        // $result = file_put_contents($path, $image); 
        // too but still not working

        $response = array(
            'status' => 'success',
        );
        return Response::json( $response  );
}

答案 1

干预图像使用file_get_content函数获取二进制数据:参考:图像::make

您的控制器应如下所示:

public function postTest() {
    $data = Input::all();
    $png_url = "product-".time().".png";
    $path = public_path().'img/designs/' . $png_url;

    Image::make(file_get_contents($data->base64_image))->save($path);     
    $response = array(
        'status' => 'success',
    );
    return Response::json( $response  );
 }

答案 2
         $file = base64_decode($request['image']);
         $safeName = str_random(10).'.'.'png';
         $success = file_put_contents(public_path().'/uploads/'.$safeName, $file);
         print $success;

推荐