如何在Laravel上传后返回随机的S3文件名?

时间:2019-06-11 14:28:55

标签: php laravel amazon-web-services amazon-s3 file-upload

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

当前,我可以上传文件,并将我认为来自S3的URL存储在数据库中。这些都不是问题。不过,发生的是S3生成了该随机文件名。我很好,但是我想以某种方式将其返回给控制器,以便将其与路径一起存储在数据库中。

我正在使用:

  • Laravel 5.8.19
  • 一个S3桶
  • league / flysystem-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();
}

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

在我成为我的人之前,我已经看过这篇文章,但是我误解了我的问题,以为他的问题与我无关。原来,此问题的答案位于:Laravel S3 image upload creates a folder with the filename automatically

答案 1 :(得分:0)

从S3上传和检索文件的最简单方法是使用Storage Facade。

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

To upload the file到Amazon S3。该文件将使用您提供的名称进行存储,因此具有可预测的文件名。您可以将文件名保存在数据库中,例如,以便以后检索。

然后,您可以稍后通过以下方式检索保存的文件:

Storage::disk('s3')->get('file.txt');

答案 2 :(得分:0)

$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');