将项目资产上传到S3

时间:2018-02-06 16:53:19

标签: php laravel amazon-s3

我想要完成的是接收请求并将每个文件保存到专用目录中的本地服务器,具体取决于它所属的资产类别。然后我想将本地存储中的url发送到数据库,这样就可以保存其临时位置,这样当用户被重定向时,他们可以在下一页上立即看到图像,但我还需要遍历所有图像和将它们保存到S3存储桶,然后使用s3中的url更新数据库字段,同时保留资产的类别。

控制器

foreach ($request->file('contract_asset') as $file) {
    $path = Storage::disk('local')->put(Carbon::now()->toDateString().'/roofing/projects/'.$project->id.'/contract-assets', $file, 'public');
    $project->addContractAsset('contract', $path);               
}

if ($request->hasFile('insurance_asset')) {
    foreach ($request->file('insurance_asset') as $file) {
        $path = Storage::disk('local')->put(Carbon::now()->toDateString().'/roofing/projects/'.$project->id.'/insurance-assets', $file, 'public');
        $project->addContractAsset('insurance', $path);                
    }
}

$files = Storage::allFiles(Carbon::now()->toDateString().'/roofing/projects/'.$project->id.'/');

dispatch(new ProcessRoofingProjectAssets($files, $project));

工作

<?php

namespace App\Jobs\Roofing;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Storage;

class ProcessRoofingProjectAssets implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $files;
    protected $project;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($files, $project)
    {
        $this->files = $files;
        $this->project = $project;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        foreach ($this->files as $file) {
            $path = Storage::disk('s3')->put('contract-assets', $file, 'public');
            $this->project->addContractAsset($path);  
        }
    }
}

模型

public function addContractAsset($category, $asset)
{
    $contract_asset_urls = json_decode($this->contract_asset_urls, true);
    $contract_asset_urls[] = ['category' => $category, 'url' => $asset];
    $this->update([
        'contract_asset_urls' => json_encode($contract_asset_urls)
    ]);

    if ($category == 'approval') {
        event(new AssociationApprovalAssetUploaded($this));
    }
}

0 个答案:

没有答案