Laravel 5.3多个文件上传

时间:2016-10-04 07:05:53

标签: php file laravel-5.3

如何在Laravel 5.3上传多个文件。如果我尝试使用1张图片,它可以正常工作,但不会上传多张图片。

这是我的代码:

 if($request->hasFile('attachment'))
 {
    foreach ($request->allFiles('attachments') as $file) {
        $file->store('users/' . $user->id . '/messages');
    }
 }

8 个答案:

答案 0 :(得分:29)

现在可以这样工作:

$files = $request->file('attachment');

if($request->hasFile('attachment'))
{
    foreach ($files as $file) {
        $file->store('users/' . $this->user->id . '/messages');
    }
}

我必须在[]属性的值之后追加name,所以:

<input type="file" name="attachment[]" multiple>

答案 1 :(得分:5)

这是Controller,用于在laravel中上传多个文件:

    public function fileUpload(Request $request)
    {
        if ($request->hasfile('filenames')) {
            foreach ($request->file('filenames') as $file) {
                $name = $file->getClientOriginalName();
                $file->move(public_path() . '/mytestfile/', $name);
                $data[] = $name;
            }
            return back()->with('Success!','Data Added!');
        }
    }

此查看文件中的资源:

<html lang="en">
<head>
    <title>Multiple Image Upload</title>
    <script src="jquery/1.9.1/jquery.js"></script>
    <link rel="stylesheet" href="3.3.6/css/bootstrap.min.css">
</head>
<body>

<div class="container lst">
    <h3 class="well">Test Muliple Image Upload</h3>

    <form method="post" action="{{url('image-upload')}}" enctype="multipart/form-data">
        {{csrf_field()}}

        <div class="input-group hdtuto control-group lst increment" >
            <input type="file" name="filenames[]" class="myfrm form-control" multiple>
            <div class="input-group-btn">
                <button class="btn btn-success" type="button"><i class="fldemo glyphicon glyphicon-plus"></i>Add</button>
            </div>
        </div>

        <button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
    </form>
</div>



<script type="text/javascript">
    $(document).ready(function() {
        $(".btn-success").click(function(){
            var lsthmtl = $(".clone").html();
            $(".increment").after(lsthmtl);
        });
        $("body").on("click",".btn-danger",function(){$(this).parents(".hdtuto control-group lst").remove();
        });
    });
</script>

</body>
</html>

答案 2 :(得分:1)

尝试这样的事情:

public function multiple_upload() {
    // getting all of the post data
    $files = Input::file('images');

    // Making counting of uploaded images
    $file_count = count($files);

    // start count how many uploaded
    $uploadcount = 0;

    foreach($files as $file) {
        $rules = array('file' => 'required');

        //'required|mimes:png,gif,jpeg,txt,pdf,doc'

        $validator = Validator::make(array('file'=> $file), $rules);

        if($validator->passes()){
             $destinationPath = 'uploads';
             $filename = $file->getClientOriginalName();
             $upload_success = $file->move($destinationPath, $filename);
             $uploadcount ++;
         }
    }
}

答案 3 :(得分:0)

如果您仍想使用刀片,可以使用:

{{ Form::open(array('url' => 'upload', 'files'=>true)); }}
{{ Form::file('gallery[]', array('multiple'=>true,'accept'=>'image/*'));  }}
{{ Form::submit();  }}
{{ Form::close();  }}

在你的控制器中:

files = $request->file('gallery');

if($request->hasFile('gallery'))
{
    foreach ($files as $file) {
       // $file->store('users/' . $this->user->id . '/messages');
        //dump($file);
    }
}

答案 4 :(得分:0)

app / Http / Controllers / FileController.php

public function store(Request $request)
{
    $this->validate($request, [

            'filenames' => 'required',

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

    ]);

    if($request->hasfile('filenames'))
     {
        foreach($request->file('filenames') as $file)
        {
            $name=$file->getClientOriginalName();
            $file->move(public_path().'/files/', $name);  
            $data[] = $name;  
        }
     }

     $file= new File();
     $file->filenames=json_encode($data);
     $file->save();
    return back()->with('success', 'Data Your files has been successfully added');

}

创建视图文件

resources / views / create.blade.php

<html lang="en">
<head>
  <title>Laravel 5.3 Multiple File Upload Example</title>
  <script src="jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="3.3.6/css/bootstrap.min.css">
</head>
<body>

<div class="container lst">
@if (count($errors) > 0)
<div class="alert alert-danger">
    <strong>Sorry!</strong> There were more problems with your HTML input.<br><br>
    <ul>
      @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
      @endforeach
    </ul>
</div>
@endif

@if(session('success'))
<div class="alert alert-success">
  {{ session('success') }}
</div> 
@endif
<h3 class="well">Laravel 5.6 Multiple File Upload</h3>
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">

  {{csrf_field()}}

    <div class="input-group flcustom control-group lst increment" >
      <input type="file" name="filenames[]" class="myfrm form-control">
      <div class="input-group-btn"> 
        <button class="btn btn-success" type="button"><i class="fldemo glyphicon glyphicon-plus"></i>Add</button>
      </div>
    </div>

    <div class="clone hide">
      <div class="flcustom control-group lst input-group" style="margin-top:10px">
        <input type="file" name="filenames[]" class="myfrm form-control">
        <div class="input-group-btn"> 
          <button class="btn btn-danger" type="button"><i class="fldemo glyphicon glyphicon-remove"></i> Remove</button>
        </div>

      </div>

    </div>
    <button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
</form>        
</div>
<script type="text/javascript">
    $(document).ready(function() {
      $(".btn-success").click(function(){ 
          var lsthmtl = $(".clone").html();
          $(".increment").after(lsthmtl);
      });
      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".flcustom control-group lst").remove();
      });
    });
</script>
</body>
</html>

Laravel 5.3 - Multiple File Upload with Validation Example

答案 5 :(得分:0)

Controller.Php / Laravel 5.7.28

   $files = $request->file('product_image_id');

   if($request->hasFile('product_image_id')){

       foreach ($files as $file){

          $name = time(). $file->getClientOriginalName();    

          $file->move('images',$name);             

         $productImage = ProductImage::create(['image'=>$name]);    

               $input ['product_image_id'] = $productImage->id;     

           }

答案 6 :(得分:0)

用一种更简单的方法解决了它。只需确保您的输入文件类型为<input type="file" name="images[]" multiple>

        $i = 0;

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

            $photo = new Photo;

            // name it differently by time and count
            $imageName = time() . $i . '.' . $file->getClientOriginalExtension();

            // move the file to desired folder
            $file->move('folderName/', $imageName);

            // assign the location of folder to the model
            $photo->image = 'folderName/' . $imageName;

            $photo->status = 1;
            $photo->save();

            $i++;

        } 

答案 7 :(得分:0)

这是我的刀片的外观:

<div class="form-group row">
                                <label for="gallery-image" class="col-sm-3 text-left control-label col-form-label">Photo</label>
                                <div class="col-md-9">
                                    {{-- <input type="file" name="images[]" multiple> --}}
                                    <input type="file" class="form-control form-control-file"
                                     id="gallery-image" value="{{ old('gallery-image') }}" required name="gallery-image[]" multiple/>
                                     <span class="below-image-upload-msg">Advised image dimensions: 1920 x 450 pixels. File size should be less than 2Mb per image.</span>
                                </div>
                                @error('image')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror
                            </div>

这是控制器中的存储功能的样子:

public function store(Request $request){
    $validation = Validator::make($request->all(), array(
        'gallery-id'    => 'required|integer|min:0',
        'gallery-image' => 'required|image|nullable|mimes:jpeg,png,jpg,gif|max:2048',
    ));
    $fileNameToStore="no-image.jpg";

    if(request('gallery-image'))
    {
        $iCount=0;
        foreach($request->file('gallery-image') as $thisImage){
            $fileNameWithExtension = $thisImage->getClientOriginalName();
            $memberName = Auth::user()->MemberProfile->member_tourist_office_name;
            

            $extension=$thisImage->getClientOriginalExtension();
            
            $fileNameToStore = $fileName.'_'.time().$iCount.'.'.$extension;

            $path= $thisImage->storeAs('public/images/members/gallery-images',$fileNameToStore);


            $isEnabled                                   = "0";   
            $galleryImage                                = new GalleryImage();
            $galleryImage->gallery_id                    = request('gallery-id');
            $galleryImage->gallery_image_caption         = " "; 
            $galleryImage->gallery_image                 = $fileNameToStore;
            $galleryImage->isEnabled                     = $isEnabled;

            $galleryImage->save();
            $iCount++;
        }
        return redirect('/galleryimage/create')->with('success', 'Image(s) successfully added to gallery!');
    }
}