0

When I use dev tool like Postman to upload file, my Express.js server using multer

import multer from 'multer';

const upload = multer();
app.post('/api/upload-file',  upload.single('file'), (req, res) => {
  console.log(req.file);
  res.sendStatus(200);
});

can parse the file correctly including mimetype field and prints

{
  fieldname: 'file',
  originalname: 'my.png',
  encoding: '7bit',
  mimetype: 'image/png',
  buffer: <Buffer ...>,
  size: 9693
}

However, when I use locust (for load testing, and it is requests backed) to upload same file by both of these two methods:

from requests_toolbelt.multipart.encoder import MultipartEncoder

@task
def upload_img_1(self):
    file = open('path/to/my.png', 'rb')
    self.client.post(
        '/api/upload-file',
        files={'file': file})

@task
def upload_img_2(self):
    file = open('path/to/my.png', 'rb')
    m = MultipartEncoder(
        fields={'file': ('my.png', file, 'image/png')})
    self.client.post(
        '/api/upload-file',
        files={'file': m})

The mimetype I got in my Express.js server are text/plain which is wrong.

{
  fieldname: 'file',
  originalname: 'my.png',
  encoding: '7bit',
  mimetype: 'text/plain',
  buffer: <Buffer ...>,
  size: 9693
}

How to get correct mimetype?

Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267
  • 1
    hi! locust uses the requests package under the hood. maybe if you check its documentation, or google it in the context of requests rather than locust? or maybe all you need to do is add headers={"content-type": "image/png"} as a parameter to your .post call (not sure though) – Cyberwiz Nov 18 '20 at 07:47
  • @Cyberwiz thanks, I am aware of it. I actually made so far based on other `requests` demo. The right one I need for file uploading is `'Content-Type': 'multipart/form-data'`, however, [it is not supposed to set directly in the Python version header](https://stackoverflow.com/questions/17415084/multipart-data-post-using-python-requests-no-multipart-boundary-was-found), otherwise I will get `Multipart: Boundary not found` error in my Express.js server side. – Hongbo Miao Nov 18 '20 at 08:30
  • ok! Unfortunately I've never posted images myself so I dont know what to say :) – Cyberwiz Nov 18 '20 at 09:37

1 Answers1

3

Finally made it by

def upload_img(self):
    file = open('path/to/my.png', 'rb')
    files = {
        'file': ('my.png', file, 'image/png'),
    }
    self.client.post(
        '/api/upload-file',
        files=files)

This time the Express.js server can get mimetype file as image/png correctly.

Hope it will help people who might same issue in future.

Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267