'How to load a local image by axios and send it to a server with express-fileupload

This is the reading file process. The filePath is a specific JPG file path(such as /xxx.jpg).

const fileStream = fs.createReadStream(filePath);

Then I start to send it to an API

async function upload(fileData) {
  const formData = new FormData(); 
  const fileArr = [];
  fileArr.push(fileData);
  formData.append("img", fileArr[0]);
  const result = (
    await axios.post(
      imgHosting,
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    )
  ).data;
  return result;
}

This is my API code.

app.post('/upload', (req, res) => {
    try {
        if (!req.files) {
            console.log('test');
            const data = {
                code: 404,
                status: "No file uploaded",
                link: "undefined"
            };
            res.json(data);
        } else {
            console.log('uploading...');
            let img = req.files.img; 
            let md5 = crypto.createHash('md5').update(img.name).digest('hex'); 
            let ext = path.extname(img.name);
            const cryptedName = `${md5}${ext}`;
            const uploadPath = path.join(__dirname, '../uploads', cryptedName);
            console.log(uploadPath);//? debug
            img.mv(uploadPath); 
            const data = {
                code: 200,
                status: "upload ok",
                link: "http://my-server-ip/pic/" + md5 + ext
            };
            res.json(data);
        }
    } catch (err) {
        res.status(500).send(err);
    }
});

The sender Node.js and the API Node.js are on the same ECS server. I don't know if this will cause any problems. But I can receive the JSON data of the following reply:

0|chatbot  | url is: undefined
2|pic-bed  | test
0|chatbot  | { code: 404, status: 'No file uploaded', link: 'undefined' }
0|chatbot  | No file uploaded

I think the problem should be that the data I send to the API is not in file format, but I don't know how to send the local JPG file directly to express-fileupoad. It also doesn't seem to support importing files directly through the file path?

This is my first time to ask questions in stackoverflow. Please forgive me if there is any non-compliance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source