How to send a picture generated in the PIL through a POST request in the format multipart / form-data. Here is the image transfer code

requests.post(upload_url, files = {'file': open(filename, 'rb')}) 

The task is to transfer the image without saving it as a separate file.

Tried through BytesIO. Does not work.

 img = pic_gen.gen_obj(parcer.main()) #Создаю изображение buf = io.BytesIO() img.save(buf, format='PNG') buf.seek(0, 0) #a = io.BufferedReader(buf) album_id = ID альбома group_id = ID группы token = 'ТОКЕН' api = vk.API(vk.Session(access_token=token), v=5.92) upload_url = api.photos.getWallUploadServer(group_id=group_id)['upload_url'] resp = requests.post(upload_url, files = {'file': buf.getvalue()}).json() s = api.photos.saveWallPhoto(group_id=group_id, server = resp['server'], photo= resp['photo'], hash = resp['hash']) api.wall.post(owner_id = -group_id, message="Test!", attachments=f"photo{s[0]['owner_id']}_{s[0]['id']}") 
  • Save the image as to a file, but not to a file, but to the object io.BytesIO - andreymal pm
  • I tried it, but it does not work. - Voziyan Vladislav pm
  • I also tried it, and it works for me for the last three years. So you somehow did not try, do not tell how? - andreymal
  • Maybe I have a special case. I upload a picture via POST request VK API. When I use the construct to open the file, everything works. But when I replace it with io.BytesIO, it gives an error. PS If you tell me how to add a code to a comment, I will be grateful - Voziyan Vladislav
  • Error text is a big secret? Add code to the question text, not to the comment. - andreymal

1 answer 1

 from io import BytesIO import requests from PIL import Image im = Image.new('RGB', (128, 128), (255, 0, 0, 255)) # [вставить сюда код усердного рисования картинки] fp = BytesIO() im.save(fp, format='PNG') # Переключаем позицию чтения в начало файла, чтобы # requests смог его прочитать fp.seek(0) requests.post( upload_url, # Капризные серверы могут запросить имя файла # и MIME-тип — укажем их # (для JPEG соответственно нужно указать image/jpeg) files={'file': ('photo.png', fp, 'image/png')}, ) 
  • Thank you very much. 3rd day I struggle with the decision. And really, it all came down to MIME. - Voziyan Vladislav