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

问题描述 投票:0回答:11

我通过 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  );
}
php laravel laravel-4
11个回答
26
投票

Intervention Image使用file_get_content函数获取二进制数据: 参考:Image::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  );
 }

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

10
投票
$data = Input::all();
$png_url = "perfil-".time().".jpg";
$path = public_path() . "/img/designs/" . $png_url;
$img = $data['fileo'];
$img = substr($img, strpos($img, ",")+1);
$data = base64_decode($img);
$success = file_put_contents($path, $data);
print $success ? $png_url : 'Unable to save the file.';

5
投票

这是一个很容易犯的错误。

您错误地使用了 public_path。应该是:

$path = public_path() . "/img/designs/" . $png_url;

另外,我会避免使用您发送图像的方法。查看表单中正确的上传并使用 Laravel 的 Input::file 方法。


3
投票

我的解决方案是:

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);
        Storage::disk('local')->put('imgage.png', $image);
        $storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
        echo $storagePath.'imgage.png'; 
        $response = array(
            'status' => 'success',
        );
        return Response::json( $response  );
}

3
投票

在公共文件夹image中存储或保存base64图像并返回文件路径。

    $folderPath = public_path() . '/' . 'images/';
    $image_parts = explode(";base64,", $image);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $uniqid = uniqid();
    $file = $folderPath . $uniqid . '.' . $image_type;
    file_put_contents($file, $image_base64);
    return $file;

1
投票

我正在做的是使用基本方法

$file = base64_decode($request['profile_pic']);
            $folderName = '/uploads/users/';
            $safeName = str_random(10).'.'.'png';
            $destinationPath = public_path() . $folderName;
            file_put_contents(public_path().'/uploads/users/'.$safeName, $file);

           //save new file path into db
            $userObj->profile_pic = $safeName;
        }

0
投票

实际上,

Input::all()
返回
array
输入,因此您有以下内容:

$data = Input::all();

现在您的

$data
是一个数组而不是对象,因此您尝试将图像作为对象访问,例如:

$data->base64_image

所以,它不起作用。你应该尝试使用:

$image = $data['base64_image'];

由于可以从

base64_image
访问它 (
$_POST
),那么
Input::file('base64_image')
将不起作用,因为
Input::file('base64_image')
检查
$_FILES
数组,但在您的情况下它不存在。


0
投票

这是我从base_64上传文件的解决方案。

    public static function uploadBase64File(Request $request, $requestName = 'imageData', $fileName = null, $uploadPath = 'uploads/images/')
    {
        try {
                $requestFileData = $request->$requestName;

                // decode the base64 file
                $file = base64_decode(preg_replace(
                    '#^data:([^;]+);base64,#',
                    '',
                    $request->input($requestName)
                ));

                if (in_array($file, ["", null, ' '])) {
                    return null;
                }

                //handle base64 encoded images here
                if ($fileName == null) {
                    $fileName = Str::random(10);
                }

                $extension = '.' . explode('/', explode(':', substr($requestFileData, 0, strpos($requestFileData, ';')))[1])[1];

                $filePath = $uploadPath . '' . $fileName . '' . $extension;

                // dd($extension);
                if (!File::exists(public_path($uploadPath))) {
                    File::makeDirectory(public_path($uploadPath), 0777, true);
                }

                // dd($filePath);
                $ifImageUploadSuccessful = File::put(public_path($filePath), $file);

                if (!$ifImageUploadSuccessful) {
                    return null;
                }

                return '/' . $filePath;
            // throw new Exception("Unable To upload Image");
        } catch (Exception $e) {
            // dd($e);
            throw new Exception($e->getMessage());
        }
}

0
投票

让我们改进您的代码,好吗?!

使用以下代码可以让您获得以下能力:

  1. 动态获取文件扩展名而不是静态写入文件
  2. 定义你喜欢存储它们的位置(我提供了两种方式供你选择)
// Your incoming base64 image from form
$image_64 = $request->input('image');

// Get extension
$extension = explode('/', explode(':', substr($image_64, 0, strpos($image_64, ';')))[1])[1];
$replace = substr($image_64, 0, strpos($image_64, ',')+1);
$image = str_replace($replace, '', $image_64);
$image = str_replace(' ', '+', $image);

// Give image a name
$imageName = Str::random(10).'.'.$extension;

// Store in public folder (or public_html in live server)
file_put_contents(public_path('images/'.$imageName), base64_decode($image));

// If you want to store in storage folder use this line instead
// Storage::disk('public')->put('images/'.$imageName, base64_decode($image));

// Store image name in DB
$model->image = 'images/'.$imageName;

快乐编码。


-1
投票

我已经做到了!!

我更换了

$data->base64_image
$_POST['base64_image']
,然后使用
$result = file_put_contents($path, $image);
而不是
Image::make($image->getRealPath())->save($path);

但这看起来不像 Laravel 的方式。我你还有另一种看起来更优雅的方式请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.