1

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.');
              }
            });
        }
      }
    });
4
  • Check PHP ini settings for max_upload_size for start. Commented Aug 18, 2017 at 5:44
  • Check this stack answer, might the same issue you are facing. Commented Aug 18, 2017 at 5:53
  • I have increased the max_upload_size = 200M and max_file_uploads = 100 than also i am not reiceving any data and i am getting error from server undefined index title at line number 1 in php code Commented Aug 18, 2017 at 6:23
  • So your actual problem now resolved. For undefined index title at line number 1, post OR check your master blade file code for title index Commented Aug 18, 2017 at 7:05

1 Answer 1

0

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 using XMLHttpRequest() 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 your php.ini.

Hope this helps you.

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.