php - 使用 HTML 表单、cURL 和 PHP 将文件上传到 Imageshack API

标签 php curl imageshack

我在将文件上传到 Imageshack 的 API 时遇到了一些问题。我使用 multipart/form-data 表单来获取文件。

索引.php:

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="fileupload"/>
    <input type="submit" value="Go"/>
</form>

通常我对此没有问题,但是数据必须发送到 http://imageshack.us/upload_api.php并且响应在他们的服务器上以 XML 样式的 HTML 页面返回,所以我真的无能为力。所以我决定通过 PHP cURL 脚本传递表单并在同一页面上获得响应。

上传.php:

<?php
    $url = 'http://imageshack.us/upload_api.php';
    $key = '4BEILRTV5ff57ecb70867e8becb2c4b5e695bdb4';
    $max_file_size = '5242880';
    $temp = $_FILES["fileupload"]["tmp_name"];
    $name = $_FILES["fileupload"]["name"];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);

    $post = array(
        "fileupload" => '@' . $temp,
        "key" => $key,
        "max_file_size" => $max_file_size
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
    echo $response;
?>

起初我遇到了一堆错误,但现在我没有得到任何回应。甚至没有错误。

任何关于使用此方法的建议都会很棒!

最佳答案

我必须将“格式”=>“json”包含在发布选项中并使用 json_decode 来解析信息。这是 upload.php 脚本。

<?php
    $url = 'http://imageshack.us/upload_api.php';
    $key = '4BEILRTV5ff57ecb70867e8becb2c4b5e695bdb4';
    $max_file_size = '5242880';
    $temp = $_FILES["fileupload"]["tmp_name"];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_URL, $url);

    $post = array(
        "fileupload" => '@' . $temp,
        "key" => $key,
        "format" => 'json',
        "max_file_size" => $max_file_size,
        "Content-type" => "multipart/form-data"
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
    $json_a=json_decode($response,true);
    echo $json_a[links][image_link];
?>

关于php - 使用 HTML 表单、cURL 和 PHP 将文件上传到 Imageshack API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14201745/

相关文章:

PHP 和 MySQL : how to narrow down the tag search result?

c - 尽管一切看起来都正确,但仍然得到 'curl/curl.h: No such file or directory'

python - 计算黑色像素比率

json - responseJSON 没有得到响应

PHP 检查 mysql 连接

php - Swift Mailer 邮件发送问题

c++ - 在C++中使用curl获取一段时间后更改的页面

php - 使用 Jquery 事件处理程序循环遍历 PHP 数组

java - 将 BitBucket REST API 与 Java 结合使用