Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Archived:How to upload a file to server with multipart/form-data

From Wiki
Jump to: navigation, search

Archived.pngAquivado: Este artigo foi arquivado, pois o conteúdo não é mais considerado relevante para se criar soluções comerciais atuais. Se você achar que este artigo ainda é importante, inclua o template {{ForArchiveReview|escreva a sua justificativa}}.

All PySymbian articles have been archived. PySymbian is no longer maintained by Nokia and is not guaranteed to work on more recent Symbian devices. It is not possible to submit apps to Nokia Store.

Article Metadata
Created: lfd (14 May 2007)
Last edited: hamishwillee (31 May 2013)

The example below shows how to upload an image.

First of all, you need to have the HTTPFileUploader library installed.

HTTPFileUploader source (

## HTTP file uploader
class HTTPFileUploader:
## Constructor
def __init__(self, host, port=80):
from httplib import HTTP = host
self.port = port
self.user = None
self.password = None = "upload/uploader.php"
self.fields = {}
self.http = HTTP(, self.port)
self._result = None
## Set user and password
def setLogin(self, user, password):
self.user = user
self.password = password
## Select the upload page
def setPage(self, selector = 'upload/uploader.php'): = selector
## Add fields in http
def setField(self, name, value):
self.fields[name] = value
## Change the target path
def setTargetPath(self, path):
self.fields["target_path"] = path
## Upload file on http server
def uploadFile(self, aSourceFilename, aKey="file"):
from base64 import encodestring
files = ((aKey,aSourceFilename.lower(),open(aSourceFilename,"rb").read()),)
content_type, body = self.encode_multipart_formdata(self.fields, files)
if self.user != None and self.password != None:
self.http.putheader("AUTHORIZATION", "Basic " + \
encodestring("%s:%s" % (self.user, self.password)).replace("\012", ""))
self.http.putheader('Content-Type', content_type)
self.http.putheader('Content-Length', str(len(body)))
errcode, errmsg, headers = self.http.getreply()
self._result =
# could need some modification to get the answer: here I just need
# to get the 5 first characters
if self._result.strip()[0:5] == "True":
return True
return False
## Encode the form.
# @param self The object pointer.
# @param fields Sequence of (name, value) elements for regular form fields.
# @param files Sequence of (name, filename, value) elements for data to be
# uploaded as files.
# @return (content_type, body) ready for httplib.HTTP instance
def encode_multipart_formdata(self, fields, files):
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for key, value in fields.items():
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
for file in files:
key = file[0]
filename = file[1]
if len(file) > 2:
value = file[2]
value = None
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % self.get_content_type(filename))
L.append('Content-Transfer-Encoding: binary')
if value:
fp = open(filename, 'rb')
L.append('--' + BOUNDARY + '--')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
## Get the file content type
def get_content_type(self, filename):
import mimetypes
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
## Get result from server
def getResult(self):
return self._result
## HTTPS file uploader
class HTTPSFileUploader(HTTPFileUploader):
## The constructor
def __init__(self, host, port=443):
from httplib import HTTPS
HTTPFileUploader.__init__(self, host, port)
self.http = HTTPS(, self.port)

Client source:

import os
from HTTPFileUploader import * # uploader class
# path of the file to download
filePath = "001.jpg"
# new HTTPFileUploader instance
uploader = HTTPFileUploader('', port = 80) # port optional if 80
# set page
# Add fields in HTTP: ex file name for or past example
uploader.setField("fileName", os.path.split(filePath)[1])
# upload file - returns True or False.
if not uploader.uploadFile(filePath, "picture"):
print uploader.getResult()

Server source (file_uploader.php):

// In this example a directory "images" needs to be present on the same directory where
// image_uploader.php is, with the necessary rights for the script to write data inside
$content_dir = 'images/';
$filename = Null;
$filename = $_POST['fileName'];
if ($filename == Null){
$filename = $_FILES['picture']['name'];
if( !move_uploaded_file($_FILES['picture']['tmp_name'], $content_dir . $filename) ){
exit("Couldn't write the file in $content_dir");
// something when wrong
// return
echo "True";
This page was last modified on 31 May 2013, at 01:09.
74 page views in the last 30 days.