Accessing data sent as FormData using Axios

若如初见. 提交于 2019-12-25 03:18:10

问题


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 that I don't know how to access the fields in FormData when I'm in the backend.

I've sent a file using axios like this:

onUpload(): void {
    if(this.fileChosen){
      const fd = new FormData();
      fd.append('file', this.selectedFile, this.selectedFile.name);
      axios.post('http://localhost:8080/routes', fd, {
        onUploadProgress: uploadEvent => {
          console.log('Upload Progress' + Math.round(uploadEvent.loaded / uploadEvent.total) * 100 + " %");
        }
      })
      .then(
        res => {
          console.log(res);
        });
    } else {
      this.fileMsg = "You haven't chosen a file";
    }
  }
}

Then in my backend I want to access this file that I sent:

app.post('/routes', function(req, res){
    res.set("Access-Control-Allow-Origin", "*");
    // Here I want to access my file! But how?
});

回答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.



来源:https://stackoverflow.com/questions/53123204/accessing-data-sent-as-formdata-using-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!