Skip to content Skip to sidebar Skip to footer

Accessing Data Sent As FormData Using Axios

I have an application written in VueJS where I send a file, that the user uploads, to the backend. To do this I'm using Axios and I'm sending the file as a FormData. The problem is

Solution 1:

I had problems with using axios for file uploading so you can use the module superagent (https://github.com/visionmedia/superagent) that supports file uploading with formData. Then, in the backend, you need to use multer (https://github.com/expressjs/multer), to get the file.

In the frontend file

//Method to do the request
superagent
.post(/register")
.attach("avatar", uploadedImage)

uploadedImage has the image content that you get in the VueJS component

In the backend file

var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
import fs from 'fs-extra'

router.post('/register', upload.single('avatar'), (req, res, next) => {
    return fs.readFile(req.file.path)
            .then(content => {
                // The content of the file
            })
}

With this code, everytime you upload a file to /register with the file content in the formdata, your image will be stored in /uploads folder on your backend. Please note that the image key must be the same in the frontend and backend, in this case, avatar.


Post a Comment for "Accessing Data Sent As FormData Using Axios"