Search code examples
pythonbase64pycurlbytestream

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!


Solution

  • 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()