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