如何在laravel 5中存储来自Excel工作表的图像

时间:2019-02-16 12:04:58

标签: php excel image laravel-5

我正在使用this library上传excel文件并将数据从excel存储到数据库中。.我想将图像从excel存储到存储中但没有成功..这是我的代码

 public function addExcel(Request $request)
{
    $request->validate([
'file' => 'required'
    ]);
     Excel::load($request->file('file')->getRealPath(), function ($reader) {
         foreach ($reader->toArray() as $key => $row) {
                $data['model_name'] = $row['model_name'];
                $data['part_number'] = $row['part_number'];


                if(!empty($data)) {
                    DB::table('products')->insert($data);
                }
            }
     });
     return 'done';
}

and this is my excel

1 个答案:

答案 0 :(得分:0)

它将通过此​​程序包后面使用的本机库。有关如何从excel获取图像的更多信息,这是他们的文档链接:https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/#reading-images-from-a-worksheet


    $i = 0;
    foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
        if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
            ob_start();
            call_user_func(
                $drawing->getRenderingFunction(),
                $drawing->getImageResource()
            );
            $imageContents = ob_get_contents();
            ob_end_clean();
            switch ($drawing->getMimeType()) {
                case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG :
                    $extension = 'png';
                    break;
                case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF:
                    $extension = 'gif';
                    break;
                case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG :
                    $extension = 'jpg';
                    break;
            }
        } else {
            $zipReader = fopen($drawing->getPath(),'r');
            $imageContents = '';
            while (!feof($zipReader)) {
                $imageContents .= fread($zipReader,1024);
            }
            fclose($zipReader);
            $extension = $drawing->getExtension();
        }
        $myFileName = '00_Image_'.++$i.'.'.$extension;
        file_put_contents($myFileName,$imageContents);
    }