Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/238.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将临时保存的图像上载到php_Php_Python_Python 3.x - Fatal编程技术网

如何在python中将临时保存的图像上载到php

如何在python中将临时保存的图像上载到php,php,python,python-3.x,Php,Python,Python 3.x,我有一个php页面,允许用户上传他们的照片 我想编写一个python脚本,能够从链接下载图像(并将其保存到临时文件中),然后将其上传到php 下面是php代码(get from)-这个php文件没有问题,它只是处理用户图像上传-(): 当我执行python脚本时,它显示 Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded. 我能知道为什么吗?谢谢进行一些调试。添加var

我有一个php页面,允许用户上传他们的照片

我想编写一个python脚本,能够从链接下载图像(并将其保存到临时文件中),然后将其上传到php

下面是php代码(get from)-这个php文件没有问题,它只是处理用户图像上传-():

当我执行python脚本时,它显示

Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.

我能知道为什么吗?谢谢

进行一些调试。添加
var\u转储($\u文件)并检查实际得到的内容。我认为您需要将其作为表单数据发送并添加文件名,否则PHP将没有文件名来获取扩展名。当前,您似乎只发送二进制文件内容。@MagnusEriksson我尝试了两种方法,一种是在上载之前将文件保存在我的计算机中,var dump显示正确的结果,文件大小为上载文件的大小,但是临时文件只显示0。我能知道为什么吗?你没有真正回应我的观点。在var_dump()中,您看到文件名了吗(您在帖子中没有传递文件名,但文件类型是基于该文件名的)?您是否尝试过将文件作为表单数据发布?是的,我看到了以tmp开头的文件名。这不是原始名称。这是临时文件的路径。正如您所看到的,它不包含任何文件扩展名。上载文件时,PHP读取文件内容并将其存储在临时文件中,然后手动将其移动到上载文件夹并将其重命名为真实文件名(包括扩展名)。正如我多次提到的,您需要使用表单数据(其中包括实际文件名)发布,或者您还需要以某种方式在请求中传递原始文件名并使用它。因为我似乎只是重复我自己,我退出了。。。
import requests
import base64
import tempfile

def download_file_from_url(url):

        # Stream the image from the url
        try:
                request = requests.get(url, stream=True)
        except requests.exceptions.RequestException as e:
                # TODO: log error here
                return None

        if request.status_code != requests.codes.ok:
                # TODO: log error here
                return None

        # Create a temporary file
        lf = tempfile.NamedTemporaryFile()

        # Read the streamed image in sections
        for block in request.iter_content(1024 * 8):

                # If no more file then stop
                if not block:
                    break

                # Write image block to temporary file
                lf.write(block)


        return lf



url = "http://localhost/wlox/testwp/tryupload/processupload.php"

files = {'fileToUpload': download_file_from_url('https://cnet2.cbsistatic.com/img/hjo7_UY6ykIh_9cfttUZYaiF7V0=/770x433/2017/06/21/39c814c4-4909-43e8-aa0d-89eff3aced37/apple-macbook-12-inch-2017-01.jpg')}

r = requests.post(url, files=files)

print(r.text)
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.