简体   繁体   中英

Python POST File To PHP

I have a PHP with jQuery and jqGrd web application; one of the features of the application is the ability to upload files (on the client side this is handled by jqGrid) and insert the contents into a database. This all works. My problem is I also need to provide a command-line mechanism for manual (or automated) file uploads. So I have the following Python code. The code successfully logs into my API and I can see my POST data in PHP but I'm doing something wrong handling the file.

I need to POST the file in the same way it would be via the web interface... which results in PHP's $_FILES being populated. With my code below $_FILES is empty though. Not sure what I'm missing.

import base64
import cookielib
import getopt
import os
import sys
import urllib
import urllib2
import MultipartPostHandler

...code to process command line args, log into api, get sessionId...

#
# import
#
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
headers = {'Cookie': 'PHPSESSID=' + sessionId}

params = {
    'action': 'import', 
    'import': 'api', 
    'file': sourceFile, 
    'data': base64.b64encode(open(sourceFile, "rb").read()), 
    'id': id
}

urllib2.install_opener(urllib2.build_opener(MultipartPostHandler.MultipartPostHandler))
response = urllib2.urlopen(urllib2.Request(api, params, headers))

print response.read()

Probably important to know that sourceFile is simply a string supplied on the command-line; it is not the file itself. I think this is the problem. I am sending the filename string in params['name'] and its contents in params['data']. How do I send the file as if interactively submitting it from a web form and have it in params['file']? Is this what I need to do?

=== EDIT ===
I can't use any modules but what I have imported. Thanks for alternate suggestions such as Requests though.

You probably don't need to specify data in the params, but just give a file object. try

params = {
    'id':'id',
    'file':open(sourceFile, 'rb')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM