2013-01-07 81 views
3

我在将文件上传到Imageshack的API时遇到了一些问题。我使用多部分/表单数据表单来获取文件。使用HTML表单,cURL和PHP将文件上传到Imageshack API

的index.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脚本传递表单,并在同一页面上获取响应。

upload.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; 
?> 

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

使用这种方法的任何建议都会很棒!

+0

什么错误?删除@,以便您可以看到它们 – vodich

+0

@vodich在发布代码中没有错误抑制操作符 –

+0

是的,您是对的 – vodich

回答

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]; 
?>