简体   繁体   中英

Send arguments and file with Ajax to NodeJs

I have a problem with my code and I don't see where is the problem.

I have this AJAX part which take a file from a form and an argument and send it to my nodejs server :

var layerID = 2;
var formData = new FormData($("#formid")[0]);
formData.append('layer', layerID);
  $.ajax({
     url: "http://localhost:3000/file-upload",
     type: 'POST',
     data: formData,
     cache: false,
     contentType: false,
     processData: false
  });

and i have this part with express which is supposed to receive the file and the argument:

app.use(bodyParser.urlencoded({
   extended: false
}))

app.post('/file-upload', function (req, res) {
  console.log('params: ' + req.params);
    console.log('body: ' + req.body);
    console.log('query: ' + req.query);
  upload(req, res, function (err) {
    if (err) {
      errorHandler
      return
    } else {
      successHandler
    }
  })
})

My problem is that I correctly receive the file but I don't receive the argument 'layer' in my nodejs server.

You are POSTing multipart data, but you only have a body parser for urlencoded data.

See the documentation for body parser :

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

  • busboy and connect-busboy
  • multiparty and connect-multiparty
  • formidable
  • multer

You can use packages like multiparty for parsing multipart data in following way. There are other packages as well.

Backend Code

const multiparty = require('multiparty');

         // Define POST route
 app.post('/file-upload', function (req, res) {
     const form = new multiparty.Form();

     form.parse(request, async (error, fields, files) => {
       if (error) throw new Error(error);

       try {
         const path = files.file[0].path;
         const layer = fields && fields.layer && fields.layer[0]
         const buffer = fs.readFileSync(path);

         // TODO 

         return response.status(200).send(data);
       } catch (error) {
         return response.status(400).send(error);
       }
     });
 }

You can use it this way. You can read from fields.

Client Code

const formData = new FormData();
formData.append('file', fileObj);

uploadHandler(formData) // this function will make an API call

Now you will be able to get files.file[0]

我找到了解决方案,解决方案是简单地在上传函数中移动我的 req.body 日志并像这样调用它: console.log("layer: " + req.body['layer']);

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