Search code examples
angularjslaravelfile-uploadng-file-upload

File upload in angularjs and laravel


I am using ngf-file-upload module to upload file through angularjs and laravel.

This is my html initiatior :

<div class="button" ngf-select="profile.uploadFiles($file, $invalidFiles)">Upload on file select</div> 

This is my controller in angular

      vm.uploadFiles = function(file) {
            if (file) {
                file.upload = Upload.upload({
                    url: 'http://localhost/api/uploadImg',
                    data: {file: file}
                });
            }
      }

This is my upload API code in Laravel.

public function uploadImg()
{
    $data = Input::file('file');
    return $data;
} 

My angular app is running on 9000 port and laravel in default port. The request from angular is hitting the api built in laravel but the thing is that it's missing the file. Although my request header looks suspicious in Browser's Network. Like content-type is not multipart/form-data

This is the link of danial farid js fiddle

I am using the same code, with alterations to sync with my api, that is mentioned in the fiddle.

The strange is thing that when i am giving my local API path to this fiddle then it is working fine. But it's not working on my project locally. I think there is something that i am missing on my angular side.

This is the image of param that is send when i am trying to upload file from local project

This is the image of param that is send when i am trying to upload file from fiddle to my api

My Conclusion

There is no problem in the code because I am able to upload the file from a html file( not in my angular project) that is specifically i have created to test file uploading and it's running.

BUT

It's failing when i am trying to upload through my project. I have attached the images of my console one case is working one(uploading image through random file) and other is not working case (where i am uploading file through my project).

I don't what to do next. I think there is something in my angular project that is creating a obstacle in my uploading process.


Solution

  • Interceptors

    Yes, they were creating problem in file upload because we have set headers in interceptors

    and the default headers we have set in interceptors

      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; 
    

    For every request that has been made from our angular app is going through the interceptor and the interceptor was modifying every request with these headers. So i Have to remove this header from the interceptor.

    Note

    Don't forget to add the removed header in every other request