requests - upload file from url

Viewed 140

I'm trying to upload a file to a website via an API call.

I'm able to get this working when the file is on my computer with:

import requests

url = "https://api.app.com/api/1/profile/1234/verification/44"

files = {"file": open("licence.jpg", "rb")}
headers = {
    "Accept": "application/json",
    "Authorization": "Bearer blah:blah"
}

response = requests.post(url, files=files, headers=headers)

print(response.text)

I now need to upload a document from a website that contains a secure link to the file instead of it being on my computer. Let's say the link produced is this.

secure_link = "https://secure-data.company.com?k=i1jdXN0b21lci1rZXktbWQ1PU5DNCUyRjNTand4TllrUGpNSFc3SmVtUSUzRCUzRCZYLUFtei1"

I've tried the following code below but can't seem to get it to work.

r = requests.get(get_url, stream=True)
if r.status_code == 200:
    r.raw.decode_content = True  # decompress as you read
    files = {'file': ('test.jpg', r.raw)
    }
    requests.post(post_url,headers=headers, files=files)
    
    response = requests.post(post_url, files=files, headers=headers)

    print(response.text)
1 Answers

If you are wanting it to behave the same way as your local code you can just download the file to a temporary location then hand its temp path in your files dictionary open call.

Otherwise you can just load the response to a variable then do the work the files= argument does manually

headers['Content-Length'] = len(fileContent)
headers['X-Content-Type-Options'] = 'nosniff'
headers['Content-Type'] = 'application/octet-stream'
headers['Content-Disposition'] = 'attachment; filename="' + filename + '"'
response = requests.post(url, headers=headers, data=fileContent)
Related