我正在尝试同时上传图片和视频,但无法
我试过了,但似乎不起作用,图像文件将成功上传但视频不会
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
$file = new Film();
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['file' => $file_name]);
$film->update(['path' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
if ($request->file('video')){
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['video' => $file_name]);
$film->update(['videoPath' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
答案 0 :(得分:0)
这是因为您在处理图像文件后返回响应,因此无法达到视频的条件。如果你想同时处理两个就在所有操作完成后返回。
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$film->update([
'file' => $file_name,
'path' => $file_path
]);
}
if ($request->file('video')){
$file_name = time().'_'.$request->video->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$film->update([
'video' => $file_name,
'videoPath' => $file_path
]);
}
return response()->json(['success'=>'Files uploaded successfully.']);
如果每个条件中的文件都被成功处理,您还可以添加额外的检查。
$file
变量是不必要的,它甚至没有保存,因此也可以删除。
至于它上传两次的原因,您在 ->file
条件内再次调用 video
,它应该是 ->video
。
顺便说一句,您可以通过传递多个数组项而不是为每个属性调用 update 来一次更新多个字段,这可以节省您的数据库请求。
答案 1 :(得分:0)
jech chua,谢谢它的工作,但它上传了两次图像。
也许我的刀片有问题
<form action="/film" class="form" method="POST" enctype="multipart/form-data">
@csrf
<div class="f">
<div class="sect1">
<input type="text" class="input" name="title" placeholder="Title..">
<textarea name="description" class="textarea" placeholder="Description.."></textarea>
<h2>Upload image</h2><input type="file" name="file" class="file">
</div>
<div class="dropz" id="image-upload">
<h2>Upload video</h2>
<input type="file" name="video">
</div>
</div>
<button type="submit" class="buttn">Create film</button>
</form>