如何在Laravel上传时返回随机S3文件名



我正在尝试将视频从我的Laravel应用程序上传到我的S3存储桶。上传工作正常,但现在我想获取文件的 url,并将其存储在数据库记录中。

目前,我可以上传文件,并将我认为是 S3 的 url 存储在数据库中。这些都不是问题。但是,发生的情况是S3会生成该随机文件名。我对此很好,但我想以某种方式将其返回到控制器,以便我可以将其与数据库中的路径一起存储。

我正在使用:

  • 拉维尔 5.8.19
  • S3 存储桶
  • 联盟/飞行系统-AWS-S3-v3

这是我的控制器:

public function store(Request $request)
{
    //Validate Form Data
    $this->validate($request, [
      'opponent' => 'required',
      'location' => 'required',
      'date' => 'required',
      'team_id' => 'required',
      'season_id' => 'required',
      'team_score' => 'required',
      'opponent_score' => 'required',
      'uploading_coach' => 'required',
      'periods' => 'required',
      'period_length' => 'required',
    ]);
    //Store all the text fields, not the video
    $game = new Game;
    $game->opponent = $request->input('opponent');
    $game->location = $request->input('location');
    $game->date = $request->input('date');
    $game->team_id = $request->input('team_id');
    $game->season_id = $request->input('season_id');
    $game->team_score = $request->input('team_score');
    $game->opponent_score = $request->input('opponent_score');
    $game->uploading_coach = $request->input('uploading_coach');
    $game->periods = $request->input('periods');
    $game->period_length = $request->input('period_length');
    $game->save();
    //Set up some variables needed below
    $getGameID = $game->id;
    $team_id = $game->team_id;
    $game_date = $game->date;
    //Handles the actual file upload to S3
    $theFile = $request->file('video_file');
    $name = 'game_date-' . $game_date . 'game_id-' . $getGameID;
    $theFile->storePublicly(
      'gameid:' . $getGameID . 'teamid:' . $team_id . '/' . $name,
      's3'
    );
    //Game film is now uploaded to S3, trying to get the url and store it in the db
    $url = Storage::disk('s3')->url('gameid:' . $getGameID . 'teamid:' . $team_id . "/" . $name);
    $gameVid = Game::find($getGameID);
    $gameVid->video_link = $url;
    $gameVid->save();
    return back();
}

有什么想法吗?

我在

写这篇文章之前看过这篇文章,但我误解了我的问题,认为他的问题无关。事实证明,这个问题的答案在这里找到: Laravel S3 映像上传会自动创建一个文件名为<</p>

div class="one_answers"的文件夹>

从 S3 上传和检索文件的最简单方法是使用存储外观。

Storage::disk('s3')->put('file.txt', $fileContent);

将文件上传到 Amazon S3。该文件以您提供的名称存储,因此您具有可预测的文件名。例如,您可以将文件名保存在数据库中,以便以后可以检索它。

然后,您可以稍后使用以下方法检索保存的文件:

Storage::disk('s3')->get('file.txt');
$yourFile = $request->file('<your request name for file>');
$extension = $yourFile->getClientOriginalExtension();
$newName = <new name> . $extension;
Storage::disk('s3')->put("<make a path if you want in to be saved in a folder>".$newName , file_get_contents($yourFile ), 'public');

最新更新