【问题标题】:enctype curl phpenctype 卷曲 php
【发布时间】:2013-04-03 16:06:42
【问题描述】:

我正在使用以下代码将图像上传到 imagezilla.net

<form target="my_iframe" action="http://imagezilla.net/api.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" accept="image/x-png, image/gif, image/jpeg" />
    <input type="hidden" name="apikey" value="" />
    <input type="hidden" name="testmode" value="1" />
    <input type="submit" value="Upload Image" />
</form>

这很好用,但由于跨域规则,我没有办法取回结果,所以我试图将它放入 cUrl php 中

<?php
$ch = curl_init("http://imagezilla.net/api.php?file='C:\Anti-Backlash-Nut.jpg'&apikey=''&testmode=1");
$header = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);       
curl_close($ch);
echo $output;
?>  

(第二批代码已经包含该文件作为快速测试)
我无法让 php 代码中的 Enctype 正常工作(行 $header = ...),因为它只是因为没有上传文件而返回。我做错了什么?

【问题讨论】:

    标签: php libcurl enctype


    【解决方案1】:

    这是您上传文件的方式:

    <?php
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        $post = array(
            "file"=>"@/path/to/myfile.jpg",
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
        $response = curl_exec($ch);
    ?>
    

    【讨论】:

    • 如果我自己的服务器上的带宽不受限制,我会使用此代码,因此为什么我使用 imagezilla,谢谢您的输入,将保留它作为备用不是问题
    【解决方案2】:

    您正在使用 GET 方法上传文件……但文件总是使用 POST 上传…… 为此,您必须将 @ 放在要作为帖子发送的文件名前面。

    在文件路径之前发送 @ 确保 cURL 将文件作为“multipart/form-data”帖子的一部分发送

    试试这个

    <?php
     $ch = curl_init("http://imagezilla.net/api.php?apikey=''&testmode=1");
     $post = array(
        "file"=>"@C:\Anti-Backlash-Nut.jpg",
    );
     curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $output = curl_exec($ch);       
     curl_close($ch);
     echo $output;
    ?>  
    

    【讨论】:

    • 我不得不将 CURLOPT_HTTPHEADER, $header 更改为 CURLOPT_HEADER, 0 因为它返回错误,但是现在当它成功时输出为空,如果有问题则显示结果
    • @user170324 这可能是因为 api 在成功上传时可能不会返回任何内容
    • 当我使用 form 方法时,它返回图像的服务器文件路径,但它确实将其返回为 xml,我是否需要将标头更改回 httpheader 并将内容类型添加到 xml?
    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 2015-09-18
    • 2016-08-12
    • 2012-03-07
    • 2018-05-02
    • 2011-05-15
    • 2011-05-21
    相关资源
    最近更新 更多