使用HTML表单,cURL和PHP将文件上传到Imageshack API [英] Uploading files to Imageshack API using HTML form, cURL and PHP
问题描述
我有一些麻烦上传文件到Imageshack的API。我使用多部分/表单数据形式获取文件。
I am having some trouble uploading files to Imageshack's API. I use a multipart/form-data form to get the file.
index.php:
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脚本传递表单,并在同一页面上获取响应。
Normally I would have no problem with this, however the data must be sent to http://imageshack.us/upload_api.php and the response is given back in an XML styled HTML page on their server so there's really nothing I can do with it. So I decided to pass the form through a PHP cURL script and getting the response on the same page.
upload.php:
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;
?>
一开始我得到了一堆错误,但现在我没有得到任何回应。甚至没有错误。
At first I was getting a bunch of errors, but now I don't get any response. Not even an error.
有关使用此方法的任何建议都非常好!
Any suggestions on using this method would be great!
推荐答案
我不得不在post选项中包含format=>'json',并使用json_decode来解析信息。这是upload.php脚本。
I had to include "format" => 'json' into the post options and use json_decode to parse the info. Here's the upload.php script.
<?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];
?>
这篇关于使用HTML表单,cURL和PHP将文件上传到Imageshack API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!