Laravel 5:如何将本地文件复制到Amazon S3?

clo*_*e45 5 upload amazon-s3 laravel laravel-5 laravel-filesystem

我正在Laravel 5中编写代码来定期备份MySQL数据库.到目前为止我的代码看起来像这样:

    $filename = 'database_backup_'.date('G_a_m_d_y').'.sql';
    $destination = storage_path() . '/backups/';

    $database = \Config::get('database.connections.mysql.database');
    $username = \Config::get('database.connections.mysql.username');
    $password = \Config::get('database.connections.mysql.password');

    $sql = "mysqldump $database --password=$password --user=$username --single-transaction >$destination" . $filename;

    $result = exec($sql, $output); // TODO: check $result

    // Copy database dump to S3

    $disk = \Storage::disk('s3');

    // ????????????????????????????????
    //  What goes here?
    // ????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

我在网上看到的解决方案建议我做一些类似的事情:

$disk->put('my/bucket/' . $filename, file_get_contents($destination . $filename));
Run Code Online (Sandbox Code Playgroud)

但是,对于大文件,使用file_get_contents()不浪费吗?还有更好的解决方案吗?

vip*_*maa 9

你可以试试这个代码

$contents = Storage::get($file);
Storage::disk('s3')->put($newfile,$contents);
Run Code Online (Sandbox Code Playgroud)

作为 Laravel 文档,这是我发现在两个磁盘之间复制数据的简单方法


小智 7

Laravel 现在有putFile\xc2\xa0andputFileAs方法来允许文件流。

\n\n
\n

自动串流

\n\n

如果您希望 Laravel 自动管理将给定文件流式传输到您的存储位置,您可以使用 putFile 或 putFileAs 方法。此方法接受\n Illuminate\\Http\\File 或 Illuminate\\Http\\UploadedFile 实例,并将\n 自动将文件流式传输到您所需的位置:

\n
\n\n
use Illuminate\\Http\\File;\nuse Illuminate\\Support\\Facades\\Storage;\n\n// Automatically generate a unique ID for file name...\nStorage::putFile(\'photos\', new File(\'/path/to/photo\'));\n\n// Manually specify a file name...\nStorage::putFileAs(\'photos\', new File(\'/path/to/photo\'), \'photo.jpg\');\n
Run Code Online (Sandbox Code Playgroud)\n\n

链接到文档: https: //laravel.com/docs/5.8/filesystem(自动流式传输)

\n\n

希望能帮助到你

\n


the*_*ter 6

有一种方法可以复制文件而无需将文件内容加载到内存中.

您还需要导入以下内容:

use League\Flysystem\MountManager;
Run Code Online (Sandbox Code Playgroud)

现在您可以像这样复制文件:

$mountManager = new MountManager([
    's3' => \Storage::disk('s3')->getDriver(),
    'local' => \Storage::disk('local')->getDriver(),
]);
$mountManager->copy('s3://path/to/file.txt', 'local://path/to/output/file.txt');
Run Code Online (Sandbox Code Playgroud)


use*_*841 5

您始终可以通过执行以下操作来使用文件资源来流传输文件(建议用于大文件):

Storage::disk('s3')->put('my/bucket/' . $filename, fopen('path/to/local/file', 'r+'));
Run Code Online (Sandbox Code Playgroud)

这里提出了另一种建议。它使用Laravel的Storage门面读取流。基本思想是这样的:

    $inputStream = Storage::disk('local')->getDriver()->readStream('/path/to/file');
    $destination = Storage::disk('s3')->getDriver()->getAdapter()->getPathPrefix().'/my/bucket/';
    Storage::disk('s3')->getDriver()->putStream($destination, $inputStream);
Run Code Online (Sandbox Code Playgroud)