Node js file upload Content-Type reduces when sending to api

Viewed 45

I have created an axios call in my node js files it is getting the image right but when it is sent to api there is no file & the Content-Type is very smaller than the real size.

The way i am sending the file:

 axios.post('http://api.site.com', 
   req.files.files,
  {     
      headers: 
          {
              'Content-Type': 'multipart/form-data',
          }   
      } )
      .then(function(result) {
         console.log(result.data);

      }) .catch(function(){ 
        console.log('FAILURE');

      });
           return res.json({"status":"success","message":"success"})

The req.files console log:

{                                                                  
  files: {
name: 'Group4.png',
data: <Buffer >,
size: 203091,
encoding: '7bit',
tempFilePath: '/tmp/tmp-1-1658204721135',
truncated: false,
mimetype: 'image/png',
md5: '5dd1c4edd7ca59c8e05550ebace12fd8',
mv: [Function: mv]
  }
 }

The header that is sent to api:

 headers: {
  Accept: 'application/json, text/plain, */*',
  'Content-Type': 'multipart/form-data',
  'User-Agent': 'axios/0.21.4',
  'Content-Length': '212',

Also i am using Cors,body parser,express-file-upload and express plugins. It would be great if someone can help me with it.

1 Answers

You can try with multer. Just try once with below codes. Ref this link https://www.section.io/engineering-education/uploading-files-using-multer-nodejs/

const multer  = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})
const upload = multer({storage: storage})

router.get('/', function(req, res, next) {
   // get your file inside /uploads
});

router.post('/profile', upload.single('avatar'), function (req, res, next) {
   // write your rest of the code like save it on db etc.
  
})
Related