我仍在学习创建API以使用Laravel 5.7上传多张图片。当我尝试通过邮递员上传一张图像时,该图像可以存储在数据库中,但是当我尝试上传两个或更多图像时,它不能存储在数据库中。我在邮递员中没有收到这个错误,但在邮递员中预览了重定向到我的登录页面。
这是我的控制者:
$this->validate($request, [
'filename.*' => 'image|mimes:jpeg,png,jpg|max:2048'
]);
if($request->hasfile('filename'))
{
$images=array();
foreach($request->file('filename') as $image)
{
$photo_name = time().'_'.$request->input('fa_transaction_id').'.png';
$destinationPath = public_path('/uploads/workphotos');
$image->move($destinationPath, $photo_name);
$img_url = asset('/uploads/workphotos/'.$photo_name);
$data = new FA_Transaction_photo();
$data->fa_transaction_id = $request->input('fa_transaction_id');
$data->user_id = $request->input('userid');
$data->photo_name = $photo_name;
$data->photo_url = $img_url;
$data->save();
array_push($images,$img_url);
}
有人可以帮助我吗?或任何人都可以教我该怎么做? 谢谢
答案 0 :(得分:0)
您犯了小错误,请再次检查代码
在循环中返回response()-> json
所以只有第一张图像被上传和存储,然后请求返回响应
按如下所示更改您的代码:
use Illuminate\Support\Facades\Storage;
$validator = Validator::make($request->all(),
['userid'=>'required',
'fa_transaction_id'=>'required',
'filename' => 'array',
'filename.*' => 'image|mimes:jpeg,png,jpg|max:2048'
]);
if($validator->fails())
{
return response()->json(['message'=>$validator->errors()->all(),'success'=>0]);
}
$trans = FA_transaction::where('fa_transaction_id', $request->fa_transaction_id)->first();
if($trans){
$this->validate($request, [
'filename.*' => 'image|mimes:jpeg,png,jpg|max:2048'
]);
if($request->hasfile('filename'))
{
$images=array();
foreach($request->file('filename') as $image)
{
$photo_name = time().'_'.$request->input('fa_transaction_id').'.png';
$destinationPath = public_path('/uploads/workphotos');
$image->storeAs($destinationPath,$filename);
$img_url = asset('/uploads/workphotos/'.$photo_name);
$data = new FA_Transaction_photo();
$data->fa_transaction_id = $request->input('fa_transaction_id');
$data->user_id = $request->input('userid');
$data->photo_name = $photo_name;
$data->photo_url = $img_url;
$data->save();
array_push($images,$img_url);
}
return response()->json(['message'=>'Upload Successfully ','success'=>1,'images'=>$images]);
}else{
return response()->json(['message'=>'No Files ','success'=>0]);
}
}
将此标头添加到邮递员中
Content-Type:multipart / form-data