douyiji3919 2013-05-21 09:58
浏览 29
已采纳

在$ _FILES中从本地python将文件发送到远程php

Preface: I started learning Python one month ago, please don't yell at me :)
I have a full developed site written in PHP, with all the functions I need with pages to insert "stuff" in the database. I am developing a command line program to insert the same thing and send them to the PHP scripts in the $_POST array, but I have no idea on how to send the file so that it would come up in the $_FILES array.

Here is what I have so far:

I send the $_POST values using the urllib modules and it works just fine

import urllib.request
import urllib.parse
data=urllib.parse.urlencode({"hello":"Yo!", "some":"AlphaBetaParkingLot"})
data=data.encode('utf_8')
request=urllib.request.Request("http://www.site.it/read_from_py.php")
f=urllib.request.urlopen(request, data)
out=f.read().decode('utf-8')
if out[0]=="1":
    print("Connection acquired!")
else:
    print("No connection!")
    print("Exit!")
    #Then actually exit!

...I read the filename from the local computer by prompting a choose file dialogbox...

from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw()
filename=askopenfilename()

...but then I have no idea on what to do with the filename. I have looked around and I have seen no way on how to send this to the $_FILES in PHP.

I have a "dirty" solution: creating a temporary html with a form just with the file and make it choose from there, but I was wondering if there was a cleaner solution.

Thanks!

P.S. If you are wondering if I have all the things I need in the PHP scripts, why would I need this Python program? Well, you would be correct, I wouldn't need it but it's not up to me...

  • 写回答

1条回答 默认 最新

  • douren2831 2013-05-21 10:06
    关注

    Try Like This

    import urllib,MultipartPostHandler,urllib2,cookielib
    cookies = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler.MultipartPostHandler)
    urllib2.install_opener(opener)
    login = urllib.urlencode(dict(admin_user='admin',admin_pass='****'))
    o=opener.open('http://some_domain_name.com/admin/index.php',login)
    print o.read()
    raw_params={"adtitle":"sample title",
            "area":"sample area",
            "addesc":"<p>sample post</p>",
        "pic[0]":open("indian_eye.jpg", "rb"), #File Goes Here
        "pic[1]":open("nature.jpg", "rb"),
            "subcatid":"1",
        "do":"post",
            }
    url="http://YOUR.php?cityid=15&subcatid=1"
    opener.open(url, raw_params)
    

    Hope it works!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器