http post goes into $_REQUEST instead into $_FILES


C

cerr

Hi,

I have a Python script that is executing an http POST to transfer a file from the client to the server. I have achieved this with below code:

from binascii import hexlify, unhexlify
from httplib import HTTPConnection, HTTPException
import os
import hashlib
import socket
import urllib2
import time
import subprocess

import MultipartPostHandler

def post_file(filename, data):
try:
wakeup()
socket.setdefaulttimeout(TIMEOUT)
#create multipartpost handler
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
#set POST arguments
host = HOST
func = "post_file"
fname = filename
#assemble post URL
url = "http://{0}{1}".format(host, URI)
print "POSTING "+fname
#assemble multipart header
data = {"data":data,"f":func,"fname":filename}
#execute POST
response = opener.open(url, data, timeout=TIMEOUT)
#reads server return value
retval = response.read()
print retval
if "SUCCESS" in retval:
return 0
else:
print "RETVAL: "+retval
return 99
except Exception as e:
print "EXCEPTION time "+str(time.time())+" - "+str(e)
return 99

but my problem is, the data gets posted to the sever but arrives in the `$_REQUEST` array and I'm expected to post stuff so that it arrives in the `$_FILES` array (this is a LAMP server). How do I need to modify my code to deliver it correctly?

Thank you,
 
Ad

Advertisements

P

Piet van Oostrum

cerr said:
Hi,

I have a Python script that is executing an http POST to transfer a file from the client to the server. I have achieved this with below code:

but my problem is, the data gets posted to the sever but arrives in
the `$_REQUEST` array and I'm expected to post stuff so that it
arrives in the `$_FILES` array (this is a LAMP server). How do I need
to modify my code to deliver it correctly?

MultipartPostHandler only works like that if you give it a real file.

Like:

myfile = open('test.txt')
data = {'file': myfile}
response = opener.open(url, data)

'file' will be the key in the $_FILES array.

If you want to 'fake' a file by supplying your own contents and fake
filename, you can better use the code from Doug Hellmann:
http://pymotw.com/2/urllib2/#uploading-files

If you don't want to use his StringIO trick you could even add a new
method add_fake_file like this:

def add_fake_file(self, fieldname, filename, body, mimetype='text/plain'):
"""Add a fake file to be uploaded."""
self.files.append((fieldname, filename, mimetype, body))
return

and then use it like:

form.add_fake_file('file', 'test1.txt', 'This is a test.')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top