I'm trying to upload a file 32+ MB to a server using an API. The only restriction I have is that can only use built-in modules. I have seen many examples using requests
library, but I'm trying to solve with urllib
. Using curl
as PoC, I did the job like this:
curl -v --request POST --url 'https://domain/upload/long-string/' --form 'apikey=my-api-key' --form 'file=@my-file.extension'
Using urllib
, I wrote the code below, but it doesn't work, because the server always returns a 400
error:
import urllib
def post_bigfile(upload_url, file, auth, timeout):
headers = {'Accept': '*/*', 'Content-Type': 'multipart/form-data'}
data = {'file': file, 'apikey': auth}
req = urllib.request.Request(upload_url, headers=headers,
data=urlencode(data).encode('utf-8'), method='POST')
return urllib.request.urlopen(req, timeout=timeout)
post_bigfile('https://domain/upload/long-string/', open('my-file.extension','rb'), 'my-api-key', 20)
I have tried using different values of Content-Type
and Accept
, but it still doesn't work. What could I possibly doing wrong? Is there another built-in module I could use to better solve this problem?