【发布时间】:2019-10-26 00:18:04
【问题描述】:
我正在尝试将视频从我的 Laravel 应用程序上传到我的 S3 存储桶。上传工作正常,但现在我想获取文件的 url,并将其存储在数据库记录中。
目前,我可以上传文件,并将我认为来自 S3 的 url 存储在数据库中。这些都不是问题。但是会发生什么是 S3 生成该随机文件名。我对此很好,但我想以某种方式将它返回给控制器,以便我可以将它与数据库中的路径一起存储。
我正在使用:
- Laravel 5.8.19
- 一个 S3 存储桶
- 联赛/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();
}
有什么想法吗?
【问题讨论】:
-
请注意,如果有人不上传
video_file,您的代码将失败;您的验证没有将其标记为required,因此在某些情况下$theFile可能是null,因此$theFile->storePublicly()会引发错误。另外,您不需要重新查询Game::find($getGameID);;你已经有了$game,你可以直接打电话给$game->gameVid = $url; $game->save(); -
感谢您的验证。我试图让上传正常工作,所以我匆匆完成了一点,但现在是时候添加它了。另外,感谢关于 $game 的建议。我不确定这是否会奏效,但我很高兴知道它会奏效。
-
没问题 :) 我知道这些建议对实际答案没有影响,这就是我将它们作为评论留下的原因。是的,在您的代码中,
$game和$gameVid在数据库中是相同的记录。您的操作方式只是稍微不那么理想,所以不是一个大问题,但无论如何都要注意。
标签: php laravel amazon-web-services amazon-s3 file-upload