Last active
October 7, 2019 07:26
-
-
Save imvaskii/4a941fa27937becbad80bb54f096a39e to your computer and use it in GitHub Desktop.
Python script to upload file using curl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def upload_file(self, file_path, upload_url): | |
""" | |
Upload file using curl | |
based on https://github.com/Lispython/pycurl/blob/master/examples/file_upload.py | |
:param file_path: | |
:param upload_url: | |
:return: abs file url path of uploaded file. | |
""" | |
if file_path is None or not os.path.exists(file_path): | |
print("File '{}' cant be uploaded".format(file_path)) | |
return | |
c = pycurl.Curl() | |
# Set curl session option | |
c.setopt(pycurl.URL, upload_url) | |
c.setopt(pycurl.UPLOAD, 1) | |
c.setopt(pycurl.READFUNCTION, open(file_path, 'rb').read) | |
# Set size of file to be uploaded. | |
c.setopt(pycurl.INFILESIZE, os.path.getsize(file_path)) | |
# c.perform() doesn't return anything, | |
# you need to configure a file-like object to capture the value. | |
# A BytesIO object would do, you can then call .getvalue() on that | |
# after the call completes: | |
data = BytesIO() | |
c.setopt(c.WRITEFUNCTION, data.write) | |
# Start transfer | |
print("\nUploading file {} to url {}\n".format(file_path, upload_url)) | |
# Perform a file transfer. | |
c.perform() | |
c.close() | |
# abs url path of the upload file | |
return data.getvalue().decode("UTF-8") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment