LoginSignup
3
0

More than 3 years have passed since last update.

特定のディレクトリにある画像ファイルをDBに一括アップロードする

Last updated at Posted at 2018-07-13

やりたいこと

画像データをファイルで管理していたが、ELBの構成の関係でDBに上げる必要が出た為、バイナリデータで一括アップロードをしたい。

実はこれは作ってもらったソースである事は内緒である。

頻繁ではないけど、何かと使うことがある機会があるソースかもしれなくて、役に立てればいいなぁと思ったので公開します。

条件

  • バイナリデータである事
  • IDと紐付いていること

ディレクトリ構造

/public/uploads/items/以下はIDの中に連番で画像が格納されていた。

/public/uploads/items/{ID}/jpeg/1.jpg
/public/uploads/items/{ID}/jpeg/2.jpg

テーブル構造

CREATE TABLE `images` (
  `image_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id` int(5) unsigned NOT NULL,
  `image` longblob NOT NULL,
  `image_name` varchar(255) NOT NULL DEFAULT '',
  `image_alt` varchar(100) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`image_id`),
) ENGINE=InnoDB AUTO_INCREMENT=466 DEFAULT CHARSET=utf8;

完成ソース

実際に使用したソースは以下の通り

import-images.php

function filterOutCurrentDirectory($fileNames) {
    return array_filter($fileNames, function ($dirName) {
        return !in_array($dirName, ['.', '..', '.DS_Store'], true);
    });
}


$dirs = scandir('../public/uploads/items');

$facilityIdList = filterOutCurrentDirectory($dirs);

$imageFileNames = array_map(function ($id) {
    $names = scandir(sprintf('../public/uploads/items/%d/jpeg', $id));

    $filteredFileNames = filterOutCurrentDirectory($names);

    return [
      'id' => $id,
      'file_names' => $filteredFileNames
    ];
}, $facilityIdList);

$imageFullPathList = array_reduce($imageFileNames, function ($acc, $id) {
    $id = $id['id'];

    $pathList = array_map(function ($path) use ($facilityId) {
        return sprintf('../public/uploads/items/%d/jpeg/%s', $id, $path);
    }, $item['file_names']);

    return array_merge($acc, $pathList);
}, []);

print_r($imageFullPathList);

foreach ($imageFullPathList as $fullPath) {
    $user = "user";
    $pass = "admin";

    $pdo  = new PDO("mysql:host=127.0.0.1;dbname=database;charset=utf8", $user, $pass);

    $sql  = "INSERT INTO images( id, image, image_name) VALUES (:id, :image, :image_name);";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(":id", explode('/', $fullPath)[4], PDO::PARAM_STR);
    $stmt->bindValue(":image", 'data:image/jpeg;base64,' . base64_encode(file_get_contents($fullPath)), PDO::PARAM_STR);
    //     $stmt->bindValue(":image_name", (new Hashids())->encode(basename($fullPath)), PDO::PARAM_STR);
    $stmt->bindValue(":image_name", basename($fullPath), PDO::PARAM_STR);

    $stmt->execute();
}

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0