while submitting large files using jquery ajax all input fields get empty on server site php

800

I am trying to send large files to server using jquery ajax and formData. The data is received if i send 7 files with 1 mb each, but if i try to send 10 files at a time than the input field received on server site is empty, though input are send properly to server. following is my code for file upload.

//php code
public function multipleupload()
    {
        $title = $_POST["title"];
        $property_id = $_POST["propertyId"];
        $userId = $_POST["userId"];
        $albumId = $_POST["albumId"];
        $profileId = $_POST["profile_id"];

        if($albumId == "") {
            $album = new Album;
            $album->title = $title; 
            $album->property_id = $property_id;
            $album->user_id = $userId;
            $album->profile_id = $profileId;
            $album->save();

            $albumID = $album->id;
            $userId = $album->user_id;
            $folder = str_replace(" ","-",$title. '-' . date("Y-m-d_His"));
            if(!is_dir('uploads/album/'. $folder) || (!is_dir('uploads/album/'. $folder . "/original") && !is_dir('uploads/album/'. $folder . "/thumb"))) {
                mkdir('uploads/album/'. $folder);
                mkdir('uploads/album/'. $folder. "/original");
                mkdir('uploads/album/'. $folder. "/thumb");
            }
        }
        else {
            $album = DB::table("photo_album")->select('*')->where('album_id', '=', $albumId)->orderBy('id','DESC')->first();
            $folder = $album->file_path;

            $album = Album::findOrFail($albumId);
            $album->update(['title' => $title]);

            $albumID = $album->id;
        }
        $fileCount = count($_FILES["finalFiles"]['name']);
        $photos = array();
        for($i=0; $i < $fileCount; $i++) {
        if($_POST["rmImage"] == "" || !in_array($i,explode(",",$_POST["rmImage"]))) {
        $ImgFile = str_replace(" ","-",pathinfo($_FILES["finalFiles"]['name'][$i], PATHINFO_FILENAME))."-".date("Y-m-d_His").".".pathinfo($_FILES["finalFiles"]['name'][$i], PATHINFO_EXTENSION);    
        $target_original_path = 'uploads/album/'. $folder . '/original/' . $ImgFile;
        $target_thumb_path = 'uploads/album/'. $folder . '/thumb/' . $ImgFile;
        if(move_uploaded_file($_FILES['finalFiles']['tmp_name'][$i], $target_original_path))
        {
            $imagine = new Imagine\Gd\Imagine();

            $mode    = Imagine\Image\ImageInterface::THUMBNAIL_INSET;

            $thumb_size    = new Imagine\Image\Box(100, 100);

            $imagine->open($target_original_path)
                ->thumbnail($thumb_size, $mode)
                ->save($target_thumb_path);

            $size    = new Imagine\Image\Box(650, 350);

            $imagine->open($target_original_path)
                ->thumbnail($size, $mode)
                ->save($target_original_path);

                $filename = $_FILES["finalFiles"]["name"][$i];
                //$album = Album::where('user_id','=',$userId)->orderBy('created_at','DESC')->first();
                $photo_details = ['album_id' => $albumID, 
                                  'property_id' => $property_id, 
                                  'file_name' => $filename, 
                                  'created_by' => $userId, 
                                  'updated_by' => $userId, 
                                  'url' => URL::to('/').'/'.$target_original_path, 
                                  'thumb_url' => URL::to('/').'/'.$target_thumb_path, 
                                  'file_path' => $folder];
                array_push($photos, $photo_details);
        }
        else
        {
            echo '{"status":"Failure","response":[],"message":"Failed to upload property image."}';
            $status = "failure";
         }
        }   
      }

      if(count($photos) > 0) {
         $albumPhoto = PhotoAlbum::insert($photos);
      }
}  

//Jquery Code
$("#photoAlbum").click(function() {
      if($("#title").val() == '') {
       $(".error-title").show();
       $(".error-photo").hide();
      }
      else {
        if($("#preview-area ul li").size() == 0) {
            $(".error-title").hide();
            $(".error-photo").show();
        }
        else {
            $("#photoAlbum").attr("disabled", true);
            var form = $('form')[0]; // You need to use standart javascript object here
            var formData = new FormData(form);
            $.ajax({
              url: "api/multipleupload",
              type: "POST",
              data: formData,
              cache: false,
              contentType: false,
              processData: false, 
              success: function(result){
                $state.go('albums',{propertyID:  $scope.propertyId});
                toastr.success('Album Has been Added successfully.');
              }
            });
        }
      }
    });
255

Answer

Solution:

In the past I have experienced issues uploading files using Jquery ajax and FormData with some weird outputs in the server side (my question).

What solved my problem was avoiding jquery and take a more vanilla approach usingXMLHttpRequest() like so:

function save(action){
    var formElement = document.getElementById("form");
    var formData = new FormData(formElement);
    formData.append('_token', $('meta[name="csrf-token"]').attr('content'));

    var request = new XMLHttpRequest();
    request.open("POST", "{{url('myUrl')}}");
    request.send(formData);

    request.onload = function(oEvent) {
      if (request.status == 200) {
        toastr.success('Yai! Saved successfully!');
      } else {
        toastr.error('Oh oh! Something went really wrong!');
      }
      $( "#form-wrapper" ).toggleClass( "be-loading-active" );
    };
}

And in my controller I could just access files normally in the request object:

public function store(Request $request)
{
    dd($request->nameOfInput);
}

Also, as people suggested in the comments, if you are handling large files make sure your php parameters are configured accordingly in yourphp.ini.

Hope this helps you.

People are also looking for solutions to the problem: Correct way to get image pixel data in PHP?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.