Uploading a file to a form using python requests
Question: Trying to write a script that fills in an online form at this
[website](http://www.formstack.com/forms/?1455656-XG7ryB28LE) and uploads a
zip file. I have looked at [the documentation](http://docs.python-
requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file) and
[several](http://stackoverflow.com/questions/17722006/login-and-upload-file-
using-python-requests/17722134#17722134)
[other](http://stackoverflow.com/questions/22567306/python-requests-file-
upload) [posts](http://stackoverflow.com/questions/27050399/make-an-http-post-
request-to-upload-a-file-using-python-urllib-urllib2) on here but still cant
get my script to upload the file.

Here is the html source for the file upload:

    
    
    <input type="file" id="field19567427" name="field19567427"
    size="30" class="fsField fsUpload uploadTypes-jpg,jpeg,gif,png,bmp,tif,
    doc,docx,xls,xlsx,txt,mp3,mp4,aac,wav,au,wmv,avi,mpg,mpeg,zip,gz,rar,z,tgz,tar,sitx" />
    

Here is my python code(_forgive all my imports I have been trying a lot of
different approaches_):

    
    
    import urllib
    import urllib2
    import cookielib
    import webbrowser
    import os
    import base64
    import requests
    from pprint import pprint
    
    walla = "X:\\Test\\Test.html"
    my_file = open("X:\\Some_Directory\\Meh.zip", 'rb')
    values = {
        "field19567029" : "Some Company",
        "field20044433" : "Some Email",
        "field40168419" : "Some Phone Num",
        "field19567035" : "Some Code",
        "field19567303" : "Some Distance",
        "field19567306" : "Map Projection",
    
       }
    zippy = {
       "field19567427" :  my_file
        }
    
    url = "http://www.formstack.com/forms/?1455656-XG7ryB28LE"
    url2 = "http://httpbin.org/post"
    if os.path.exists(walla):
      os.remove(walla)
    r = requests.post(url, data=values, files=zippy)
    #r.status_code
    #pprint(r.json()['headers'])
    with open(walla, "w") as f:
        f.write(r.content)
    


Answer: With your specific url, you need to add some data:

    
    
    url = "http://www.formstack.com/forms/?1455656-XG7ryB28LE"
    
    session = requests.session()
    r = session.get(url)  # This can be used to determine form and viewkey values
    
    data = {
        "form": "1455656", # Added
        "viewkey": "XG7ryB28LE", # Added
        "_submit": "1", # Added
        "field19567029" : "Some Company",
        "field20044433" : "Some Email",
        "field40168419" : "Some Phone Num",
        "field19567035" : "Some Code",
        "field19567303" : "Some Distance",
        "field19567306" : "Map Projection",
       }
    
    files = {"field19567427": open("X:\\Some_Directory\\Meh.zip", 'rb')}
    
    r2 = session.post(url, data=data, files=files)
    print r2.content       
    

