简体   繁体   English

将Python POST文件转换为PHP

[英]Python POST File To PHP

I have a PHP with jQuery and jqGrd web application; 我有一个带有jQuery和jqGrd Web应用程序的PHP; 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. 该应用程序的功能之一是能够上传文件(在客户端,由jqGrid处理)并将内容插入数据库。 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. 所以我有以下Python代码。 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. 该代码成功登录到我的API,并且可以在PHP中看到我的POST数据,但是在处理文件时做错了什么。

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. 我需要以与通过Web界面相同的方式发布文件...导致填充PHP的$ _FILES。 With my code below $_FILES is empty though. $ _FILES下面的代码为空。 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; 要知道sourceFile只是命令行上提供的字符串,可能很重要; 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']. 我在params ['name']中发送文件名字符串,并在params ['data']中发送其内容 How do I send the file as if interactively submitting it from a web form and have it in params['file']? 如何发送文件,就像从Web表单以交互方式提交文件一样,并将其保存在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')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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