简体   繁体   中英

Getting null when uploading a local file from nodejs to a Laravel server

I am trying to upload a local file using NodeJs (the file is in the same directory as app.js) to a remote Laravel server but I'm getting null. For some reason the file doesn't seem to get to the server. I'm not sure what I'm doing wrong..

Here is my node app folder structure

node_app/
├── node_modules/
├── app.js
├── screenshot.jpg
├── package.json

Here is my app.js

const fs = require('fs')
const path = require('path')
const axios = require('axios')
const FormData = require('form-data')
const screenshot = require('screenshot-desktop')

let formData = new FormData()
formData.append('screenshot-file', fs.createReadStream(path.join(__dirname, 'screenshot.jpg')))

axios.post(
  `https://www.myapp.com/api/upload-screenshot`,
  formData,
  { headers: { 'content-type': 'multipart/form-data' } }
)

And here is my Laravel endpoint

class ScreenshotController extends Controller
{
    public function upload(Request $request)
    {
        // $file is null :(
        $file = $request->file('screenshot-file');

        $filename = 'screenshot.jpg';
        $file->move(storage_path('/uploads/screenshots/'), $filename);

        return $filename;
    }
}

Error: 'Call to a member function move() on null'

When the request arrives at my Laravel endpoint, there doesn't seem to be a 'screenshot-file' file submitted as it is showing null.

Also using dump($request->all()); it returns an empty array [] which means nothing has been submitted.

However doing a simple post request, it does arrive at the server

axios.post(`https://www.myapp.com/api/upload-screenshot`, {
   hello: 'asdf'
})

I finally got it to work after thoroughly reading the documentation for the node.js form-data library. So I will share it with others who might also run into this problem.

I was passing in the wrong headers, I needed to first get the headers from my formData object and then pass them on to axios like this:

function uploadScreenshot()
{
    let formData = new FormData()
    let stream   = fs.createReadStream(path.join(__dirname, 'screenshot.jpg'))

    formData.append('screenshot-file', stream)

    let formHeaders = formData.getHeaders()

    axios.post('https://www.myapp.com/api/upload-screenshot', formData, {
        headers: {
            ...formHeaders,
        },
    }).catch(error => {
        console.log(error)
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM