Laravel-API用于多个文件上传

时间:2019-02-26 08:21:13

标签: laravel laravel-5.7

我要在上传时使laravel api用于多个文件的上传,然后给出错误$ data是未定义的变量。请帮助我如何删除此错误..?

FileUploadController.php

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
    public function uploadFile(Request $request){

        $this->validate($request, [

        'user_sharing_image' => 'required',

        'user_sharing_image.*' => 'mimes:doc,pdf,docx,zip'

        ]);

        if($request->hasfile('user_sharing_image'))

         {
            foreach($request->file('user_sharing_image') as $file)

            {
                $name=$file->getClientOriginalName();

                $file->move(public_path().'/files/', $name);  

                $data[] = $name;  
            }
         }

         $file= new Detail();
         $file->title = $request->title;
         $file->info = $request->info;
         $file->user_id = $request->user()->id;
         $file->user_sharing_image=json_encode($data);

         $file->save();

        return back()->with('success', 'Data Your files has been successfully added');
    }
}

我正在使用laravel护照进行身份验证,并想存储user_id,但没有得到帮助,请帮助我如何从此代码中解决这两个问题

3 个答案:

答案 0 :(得分:0)

尝试一下

$data = [];
if($request->hasfile('user_sharing_image'))
 {
    foreach($request->file('user_sharing_image') as $key=>$file)

    {
        $name=$file->getClientOriginalName();    
        $file->move(public_path().'/files/', $name);      
        $data[$key] = $name;  
    }
 }

 $file= new Detail();
 $file->title = $request->title;
 $file->info = $request->info;
 $file->user_id = Auth::user()->id;
 $file->user_sharing_image=json_encode($data);

 $file->save();

答案 1 :(得分:0)

由于未定义$data,因此收到此错误。

foreach循环之前,您可以将其声明为$data = array();

答案 2 :(得分:0)

我认为您应该使用files方法返回文件数组:

     foreach($request->files('user_sharing_image') as $file)