簡體   English   中英

如何使用Laravel API上傳多個圖像?

[英]How to upload multiple image using laravel api?

我仍在學習創建使用Laravel 5.7上傳多個圖像的API。 當我嘗試通過郵遞員上傳一張圖像時,該圖像可以存儲在數據庫中,但是當我嘗試上傳兩個或更多圖像時,它不能存儲在數據庫中。 我在郵遞員中沒有收到這個錯誤,但在郵遞員中預覽了重定向到我的登錄頁面。

這是我的控制器:

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

有人可以幫助我嗎? 或任何人都可以教我該怎么做? 謝謝

您犯了小錯誤,請再次檢查代碼

在for循環中返回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]);

   }
 }

在郵遞員中添加此標頭

內容類型:多部分/表單數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM