拉拉维尔视频,音频和图像上传



这是我的PostsController的图片上传方法

public function store(Request $request, User $user, Image $image)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'body' => 'required'
]);

if( $request->hasFile('image') ) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)->save( public_path('uploads/images/' . $filename ) );
} 
$image = $filename;
auth()->user()->publish(
new Post(['body' => request('body'), 'image' => $image, 'user_id' => auth()->id()])
);
return redirect('/');
}

我想要一种方法来上传图像,视频和音频,以及一个用户可以上传图像或视频或音频的输入 如何在一个控制器中完成所有这些操作?

首先确定文件是视频、音频还是图像。然后决定如何进行验证。希望这会有所帮助。

if( $request->hasFile('file') ) {
		$file = $request->file('file');
		$imagemimes = ['image/png']; //Add more mimes that you want to support
		$videomimes = ['video/mp4']; //Add more mimes that you want to support
		$audiomimes = ['audio/mpeg']; //Add more mimes that you want to support
		if(in_array($file->getMimeType() ,$imagemimes)) {
			$filevalidate = 'required|mimes:jpeg|max:2048';
		}
		//Validate video
		if (in_array($file->getMimeType() ,$videomimes)) {
			$filevalidate = 'required|mimes:mp4';
		}
		//validate audio
		if (in_array($file->getMimeType() ,$audiomimes)) {
			$filevalidate = 'required|mimes:mpeng';
		}		
}
$this->validate($request, [
'file' => $filevalidate,
'body' => 'required'
]);

如果您使用的是表单请求,请尝试使用以下代码

public function rules() {
$rules = [
'some_field' => 'required',
];
//  if fileType is audio
if ($this->input('fileType') == 'audio') {
$rules['file'] = 'mimes:mp3,mp4';
}
//if fileType is video
if ($this->input('fileType') == 'video') {
$rules['file'] = 'mimes:mp4,3gp';
}
return $rules;
}

字段名称和验证规则会根据您的要求进行更改。

相关内容

  • 没有找到相关文章

最新更新