How to upload binary Binary file using http request POST submit in python

created at 03-23-2022 views: 169

problem

I recently built a project, and later, because of data submission, the historical data needs to be migrated through the program, because the content used by the historical data is the same as the new interface content, but the structure is completely different.

ps: The interface submitted here is an image file, and the way of submission is in the form of image binary file stream.

upload file with python

code

def updateImage(self, filepath):
        upload_url = "http://192.168.1.16:8999/upload/ueditor?action=uploadimage&encode=utf-8"
        header = {"Cookie": "hu_food=06237f4bd64fdfe1e111e79f43953897#1"}
        # Here is the point! When we operate the file upload,
        # Open the target file with open, and then store it in the variable upfile and store it in a dictionary. Note that the upfile here is not random. It depends on how the key used to receive the file information is defined when receiving data in the background. Must follow the server key
        files = {'upfile': open(filepath, 'rb')
                 }

        upload_data = {"id": "WU_FILE_138",
                       "name": "749.jpg",
                       "type": "image/jpeg",
                       "lastModifiedDate": "Tue Jul 21 2020 17:31:42 GMT 0800 (China Standard Time)",
                       "size": "64269"}
        ##Here is the point! When we operate file upload, the interface request parameters are directly stored in the upload_data variable,
        # When requesting, pass it directly as data
        upload_res = requests.post(upload_url,
                                   upload_data,
                                   files=files,
                                   headers=header)

        return upload_res.content.decode()
created at:03-23-2022
edited at: 03-23-2022: