2013-01-07 118 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]; 
?>