| 1 |
#! /usr/bin/env python |
| 2 |
# vi:ts=4:et |
| 3 |
|
| 4 |
import os, sys |
| 5 |
import pycurl |
| 6 |
|
| 7 |
# Class which holds a file reference and the read callback |
| 8 |
class FileReader: |
| 9 |
def __init__(self, fp): |
| 10 |
self.fp = fp |
| 11 |
def read_callback(self, size): |
| 12 |
return self.fp.read(size) |
| 13 |
|
| 14 |
# Check commandline arguments |
| 15 |
if len(sys.argv) < 3: |
| 16 |
print("Usage: %s <url> <file to upload>" % sys.argv[0]) |
| 17 |
raise SystemExit |
| 18 |
url = sys.argv[1] |
| 19 |
filename = sys.argv[2] |
| 20 |
|
| 21 |
if not os.path.exists(filename): |
| 22 |
print("Error: the file '%s' does not exist" % filename) |
| 23 |
raise SystemExit |
| 24 |
|
| 25 |
# Initialize pycurl |
| 26 |
c = pycurl.Curl() |
| 27 |
c.setopt(pycurl.URL, url) |
| 28 |
c.setopt(pycurl.UPLOAD, 1) |
| 29 |
|
| 30 |
# Two versions with the same semantics here, but the filereader version |
| 31 |
# is useful when you have to process the data which is read before returning |
| 32 |
if 1: |
| 33 |
c.setopt(pycurl.READFUNCTION, FileReader(open(filename, 'rb')).read_callback) |
| 34 |
else: |
| 35 |
c.setopt(pycurl.READFUNCTION, open(filename, 'rb').read) |
| 36 |
|
| 37 |
# Set size of file to be uploaded. |
| 38 |
filesize = os.path.getsize(filename) |
| 39 |
c.setopt(pycurl.INFILESIZE, filesize) |
| 40 |
|
| 41 |
# Start transfer |
| 42 |
print('Uploading file %s to url %s' % (filename, url)) |
| 43 |
c.perform() |
| 44 |
c.close() |