preface

If you need to send files to the server, such as uploading pictures, videos, etc., you need to send binary data.

Generally, content-type: multipart/form-data is used for uploading files. Data type, which can send files or associated message body data.

 

POST a multipart-encoded file

Basic steps for uploading files using Requests

  1. Construct the file data and open the file in binary mode through the open function
  2. Construct relevant data
  3. The request is sent, and the file data is passed in as files, and other message body data is passed in as Data, JSON, headers, and cookies
2 files = {3 'file': ('test.png', # file name 4 open('.. /file/test.png', 'rb'), # file path 5 'image/ PNG ', # file type 6 {'Expires': 9 10 data = {11 "name": R = requests. Post (url, data=data, files=files) 16 print(r.json())Copy the code

Pay attention to

The ‘file’ key in the files dictionary changes based on the name property of the upload component, not necessarily file;

As shown in the picture below, when you upload an image, you can find that two values will be passed, one is fileField and the other is Type, so your file data dict should contain two keys, fileField and Type

1 files = {2 'fileField': ('test.png', # file name 3 open('.. /file/test.png', 'rb'), # file path 4 'image/ PNG ', # file type 5 {'Expires': '0'} 1 8} # => Open the upload file and add related parameters of the fileCopy the code
Copy the code