I am experiencing a weird behaviour when trying to upload a file from Angular 5.2 to to a Laravel 5.5 application. The file data is not visible/accessible on server side.
I've tried different headers and approaches but they all seem to fail -
HTML:
<input type="file" (change)="handleFileInput($event.target.files)" multiple/>
JS:
handleFileInput(files: FileList) {
let formData = new FormData();
formData.append('file', files[0], files[0].name);
let headers = new HttpHeaders({
'Content-Type': 'application/json' // also tried 'multipart/form-data' and undefined
});
const req = new HttpRequest('POST', 'https://uploader.test/upload', formData, {headers: headers});
this.http.request(req).subscribe(res => console.log(res));
}
on Laravel side
logger('$request', [$request->all()]);
prints []
Also tried $request->file('file')
and Input::file('file')
which both return null.
The Browser's developer tools shows the following payload is submitted:
------WebKitFormBoundaryqZauUjRcPnD6wRmx
Content-Disposition: form-data; name="file"; filename="31562207_10106275826879542_6883202223082307584_n.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryqZauUjRcPnD6wRmx--
UPDATE The controller code is really super simple
public function upload(Request $request)
{
logger('$request->all()', [$request->all()]); // prints $request->all() [[]] []
logger('Input::all()', [Input::all()]); // prints Input::all() [[]] []
logger('input.file', [ Input::file('file') ]); // prints input.file [null] []
logger('request.file', [ $request->file('file')]); // prints request.file [null] []
logger('$_POST', [$_POST]); // prints $_POST [[]] []
logger('$_FILES', [$_FILES]); // prints $_FILES [[]] []
}
When I replace formData with an object:
const req = new HttpRequest('POST', 'https://uploader.test/upload', {
data: formData,
file: files[0],
test: '123'
}, {headers: headers});
this.http.request(req).subscribe(res => console.log(res));
I get [{"data":[],"file":[],"test":"123"}]
I've also tried the following workarounds (found in various forums):
- Laravel workaround -
formData.append('_method', 'PUT');
- using
http.post
instead ofhttp.request
- adding options with
contentType: false
andprocessData: false
- Already tried solutions suggested in other questions such as Angular-5 File Upload
In each one of my tests, the file data itself is not being passed on to the server.
Any help would be greatly appreciated!