Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to post an image file to other server in express js?

I tried post an image to another this server(13003) by file/toOther api, but its console.log showed just this

------file upload -------
undefined

and when I read console.log(req) then i found like this

headers: {
    accept: 'application/json, text/plain, */*',
    'content-type': 'application/x-www-form-urlencoded',
    'user-agent': 'axios/0.21.1',
    host: 'localhost:13003',
    connection: 'close',
    'transfer-encoding': 'chunked'
  },
  rawHeaders: [
    'Accept',
    'application/json, text/plain, */*',
    'Content-Type',
    'application/x-www-form-urlencoded',
    'User-Agent',
    'axios/0.21.1',
    'Host',
    'localhost:13003',
    'Connection',
    'close',
    'Transfer-Encoding',
    'chunked'
  ],

I don’t know why 13003 server received like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I use postman to post image to 13003 server, then the image file is successfully uploaded
What will be the problem?

server/routes/file.js

let express = require("express");
let router = express.Router();

let path = require('path');
let uploadDir = 'static'
let uploadForOtherDir = path.join(__dirname, '../../static');
let fs = require('fs');


const axios = require('axios')
const FormData = require('form-data')


let multer = require('multer');
let storage = multer.diskStorage({
  destination: function (req, file, callback) { 
    callback(null, uploadDir);
  },
  filename: function (req, file, callback) { 
    callback(null, 'logo-' + Date.now() + '.' + file.mimetype.split('/')[1]);
  }
});
let upload = multer({ storage: storage });


router.post('/', upload.single('logo'), function (req, res) {

  console.log("------file upload -------")
  console.log(req.file)
  res.json(req.file)

});


router.post('/toOther', async function (req, res) {
  let formData = new FormData()
  console.log('/toOther req :: ', req)
  let fileToOther = path.join(uploadForOtherDir, 'logo2.png')
  console.log('fileToOther>>>', fileToOther)
  let infor = fs.existsSync(fileToOther)
  console.log('infor>>', infor) // infor>> true
  formData.append('logo', fs.createReadStream(fileToOther))

  console.log('formData.getHeaders()', formData.getHeaders())
  let headerHere = formData.getHeaders()
  
  try {
    let result = await axios.post(
      `http://localhost:13003/file`,
      formData,
      {Headers: headerHere}
    )
    
    res.status(200).json(result.data)
  } catch (err) {
    console.log('file/toOther err', err)
  }
})

>Solution :

Looks like this is a known issue (see https://github.com/axios/axios/issues/789)

As a workaround make sure to specify the content-length header and the formData knownLength explicitly:

// ...
formData.append('logo', fs.createReadStream(fileToOther), { knownLength: fs.statSync(fileToOther).size })

const headers = {
    ...formData.getHeaders(),
    "Content-Length": formData.getLengthSync()
};

axios.post(`http://localhost:13003/file`, formData, {headers})
// ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading