3

我在将文件上传到 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;
?>

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

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

4

1 回答 1

1

我必须在帖子选项中包含“格式”=>“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];
?>
于 2013-01-28T21:04:18.207 回答