nico
nico

Reputation: 77

pyCurl - upload data in base64 to WebDav server in python

I am uploading files to a WebDav server with pyCurl and the following function:

def fileupload(url, filename, filedata, upload_user, upload_pw):
    # Initialize pycurl
    c = pycurl.Curl()

    url = url + filename
    c.setopt(pycurl.URL, url)
    c.setopt(pycurl.UPLOAD, 1)

    c.setopt(pycurl.READFUNCTION, open(filename, 'rb').read)

    c.setopt(pycurl.SSL_VERIFYPEER, 0)
    c.setopt(pycurl.SSL_VERIFYHOST, 0)
    c.setopt(pycurl.USERPWD, upload_user + ":" + upload_pw)

    # Set size of file to be uploaded.
    filesize = os.path.getsize(filename)
    c.setopt(pycurl.INFILESIZE, filesize)

    # Start transfer
    c.perform()
    c.close()

Now, I want to modify the function to upload a file coded in a base64 bytestring. How I have to modify the readfunction c.setopt(pycurl.READFUNCTION, open(filename, 'rb').read) and the filsize filesize = os.path.getsize(filename) to make this work? The base64 bytestring is provided in the variable filedata.

As an bytestream noob, my try and error approach was unfortunately not successful...

Thanks in advance!

Upvotes: 0

Views: 139

Answers (2)

Adrian8115
Adrian8115

Reputation: 33

You could simply open the file, get its content and encode it (To get the size you could again save it as a temporary file which will be deleted and get its size or just use the base64 strings length)

something like this:

class customRead:
    def __init__(self, filename):
        with open(filename, 'rb') as file:
            self.data = file.read()
        
    def get(self):
        base64_data = base64.b64encode(self.data)
        return base64_data


def get_base64_size(base64_data):
    return len(base64_data)
    

then you would change your read function to something like this:#

filebase64data = customRead(filename)

c.setopt(pycurl.READFUNCTION, filebase64data.get)

and your size func to

c.setopt(pycurl.INFILESIZE, get_base64_size(filebase64data.get()))

;)

Upvotes: 0

nico
nico

Reputation: 77

I think I found a solution with this code:

def fileupload(url, filename, filedata, upload_user, upload_pw):
    filedata = base64.b64decode(filedata).decode('ascii', 'ignore')

    # Initialize pycurl
    c = pycurl.Curl()
    url = url + filename
    c.setopt(pycurl.URL, url)
    c.setopt(pycurl.UPLOAD, 1)

    c.setopt(pycurl.READFUNCTION, StringIO(filedata).read)

    c.setopt(pycurl.SSL_VERIFYPEER, 0)
    c.setopt(pycurl.SSL_VERIFYHOST, 0)
    c.setopt(pycurl.USERPWD, upload_user + ":" + upload_pw)

    # Set size of file to be uploaded.
    filesize = len(filedata)
    c.setopt(pycurl.INFILESIZE, filesize)

    # Start transfer
    c.perform()
    c.close()

Upvotes: 0

Related Questions