Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

BabyJebus's avatar

Can not upload file to API with JavaScript, but using Postman Works.

I need my users to upload a file to our API, but whenever I run the JavaScript code I get the following error.

Call to a member function getRealPath() on null

The route is working since I am able to get the desired response with postman. Here is my JavaScript

const submitFile = () => {
        let inputFile = document.getElementById('browse-file').files[0]
        let url = `https://google.com/test`
        var data = new FormData()

        data.append('file', inputFile)
        
        axios.post(url, data)
            .then(res => {
                console.log(res)
            }).catch(err => console.log(err))
    }

Here is the line in my PHP code that is failing.

$path = file_get_contents($request->file->path());
0 likes
5 replies
MohamedTammam's avatar

Firstly, adding the proper headers for uploading a file.

const submitFile = () => {
        let inputFile = document.getElementById('browse-file').files[0]
        let url = `https://google.com/test`
        var data = new FormData()

        data.append('file', inputFile)
        
        axios.post(url, data, {headers: {'Content-Type': 'multipart/form-data'}})
            .then(res => {
                console.log(res)
            }).catch(err => console.log(err))
    }

Secondly, it's better to validate that the input is a file in the back-end

$request->validate([
	'file' => 'required|file'
]);

$path = file_get_contents($request->file->path());
MohamedTammam's avatar

@BabyJebus What's the value of

$request->validate([
	'file' => 'required|file'
]);
dd($request->file('file'));
$path = file_get_contents($request->file->path());

Please or to participate in this conversation.