Skip to content Skip to sidebar Skip to footer

Python Requests: How Can I Properly Submit A Multipart/form Post Using A File Name

I have taken a look at other questions related to multipart/form POST requests in Python but unfortunately, they don't seem to address my exact question. Basically, I normally use

Solution 1:

To upload files with the request library, you can include the file handler directly in the JSON as described in the documentation. This is the corresponding example that I have taken from there:

url = 'http://httpbin.org/post'files = {'file': open('path_to_your_file', 'rb')}

r = requests.post(url, files=files)

If we integrate this in your script, it would look as follows (I also made it slightly more pythonic):

import os
import requests
import json


folder = 'zips'
ins_id = raw_input("Please enter your member ID: ")
auth = raw_input("Please enter your API authorization token: ")
url = "https://example.api.com/upload?"
header = {"Authorization": auth}

for filename inos.listdir(folder):
    ifnot filename.endswith(".zip"):
        continue

    file_path = os.path.abspath(os.path.join(folder, filename))
    ins_id="+str(ins_id)"
    response = requests.post(
        url, headers=header, 
        files={"form_type": (None, "html"), 
        "form_file_upload": open(file_path, 'rb')}
    )
    api_response = response.json() 
    print api_response

As I don't have the API end point, I can't actually test this code block - but it should be something along these lines.

Post a Comment for "Python Requests: How Can I Properly Submit A Multipart/form Post Using A File Name"