HTTP PUT with Express.js & axios

Viewed 235

I am trying to upload a canvas from browser to server...

browser function:

function capture(canvas) {
    var canvas = document.getElementById(canvas);
    img = canvas.toDataURL()
    axios.put('/upload/'+document.title, img, {
        headers: {
          'Content-Type': 'text/plaintext'
        }
    })
}

server function:

app.use(bodyParser.urlencoded({ extended: false }));
app.put('/upload/:title', (req, res) => {
    res.status(200)
    let filename = req.params.title
    console.log(req.body)
})

When capture function runs, it does request on server, but req.body is empty. I need that body for saving to a file. Everything is working fine, but in the end, nothing gets on the server, which is my main problem. I've tried text bodies, data bodies, with various body contents, but nothing helps.

2 Answers

try using a FormData.

example (pass the canvas element as a parameter):

function fileUpload(canvas) {
    let data = new FormData();
    canvas.toBlob(function (blob) {
        data.append('data', blob);
        axios.post('/upload/'+document.title, data, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            })
            .then(res => {
                console.log(res)
            });
        });
    }

You need convert your canvas to Blob or ArrayBuffer And then send data to server in format that you fit better.

Related