Laravel视频,音频和图像上传

时间:2018-05-14 05:05:47

标签: php laravel upload

这是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('/');
}

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

2 个答案:

答案 0 :(得分:2)

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

  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;
}

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

答案 1 :(得分:0)

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

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