0

I have an ajax function where I post multiple files in an array. How can store these files? I tried the following code in controller but only the first file is being stored.

foreach ($request->photos as $imagefile) {
  $imageName = $imagefile->getClientOriginalName();
  $imagePath = public_path('folder-path/');
  $imagefile->move($imagePath,$imageName);
}

also this is how my array looks like array from ajax

as @innovin requested.

Blade File

<input name="files[]" type="file" class="form-control" accept="image/png, image/jpeg" multiple id="files">

<a href="javascript:;" class="btn btn-primary" onclick="otherUpload()">Update</a>

    function otherUpload(){
      var outputdata = [];
      var fileSelect = document.getElementById('files');
      var files = fileSelect.files;
      var formData = new FormData();
      // Loop through each of the selected files.
      for (var i = 0; i < files.length; i++) {
          var file = files[i];
          // Check the file type.
          if (!file.type.match('image.*')) {
              continue;
          }
          // Add the file to the request.
          formData.append('photos[]', file, file.name);
      }

      $.ajax({
        type: "POST",
        url: 'post-url',
        contentType: false,
        processData: false,
        dataType:'json',
        data: formData,
        success:function(data) {
          if(data.code == 1){
          console.log(data);
          fetchOtherImages();
      }
        }
      });
    }
</script>```

3
  • Please update your question with your ajax code and blade file. Commented Oct 27, 2022 at 21:21
  • @Innovin just updated. Thank you for looking into this. Commented Oct 27, 2022 at 21:28
  • 1
    Does this answer your question? Handling File Upload in Laravel's Controller Commented Oct 27, 2022 at 21:44

1 Answer 1

0

you should loop through $request->file('photos') instead of $request->photos

        if($request->hasfile('photos'))
         {
            foreach($request->file('photos') as $photo)
            {
                $name = $photo->getClientOriginalName();
                $file->move(public_path('folder-path'), $name); 
                // to store file in Storage folder:  
                //$file->storeAs('files', $name); 
            }
         }
 

note that he function GetClientOriginalName() is used to retrieve the file's original name at the time of upload in laravel, and that'll only be possible if the data is sent as array and not as a string. Hence, you must add enctype="multipart/form-data" whenever you are creating a form with input fields for files or images.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.