我正在尝试通过PHP将图像上传到IMGUR。 这是代码:
<?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'mykey' => IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
&GT;
这是我收到的错误消息:
警告:fopen(image.jpg)无法打开流:没有这样的文件或目录
我不明白这部分:$ filename =“image.jpg”; 文件名来自何处,因为它是base64生成的字符串? 谢谢, 鲍勃
答案 0 :(得分:2)
该警告是因为fopen试图从运行脚本的目录中读取文件image.jpg。 关于如何通过curl传输文件的一个很好的例子可以在这里看到
Send file via cURL from form POST in PHP
他们有$ localFile = $ _FILES [$ fileKey] ['tmp_name'];你会把$ localFile ='/ path / to / image.jpg';除了更改服务器信息并添加任何其他变量,您可能需要传递给imgur。
答案 1 :(得分:0)
更改第1行:
$filename = "image.jpg";
要:
$filename = $_FILES['uploaded_file']['tmp_name'];
然后,发布...我推荐一个类似于此的表格:
<form enctype="multipart/form-data" method="post" action="upload.php" target="my_iframe">
Choose your file here:
<input name="uploaded_file" type="file"/>
<input type="submit" value="Upload It"/>
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<script language="JavaScript">
<!--
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
}
document.getElementById(id).height= (newheight) + "px";
document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>
<IFRAME name="my_iframe" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>
如果你将所有的php放入upload.php然后在同一目录的页面上放置该表单,它就非常接近功能......除了你的源中还没有API_KEY。 您可以在此处获取API密钥:https://imgur.com/register/api_anon
最后你的php应该是这样的:
<?
if( isset($_FILES['uploaded_file']) )
{
$IMGUR_API_KEY = 'u432ewriuq3oirefuie'; //put your api key here
$filename = $_FILES['uploaded_file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
//$data is file data
$pvars = array('image' => base64_encode($data), 'key' => $IMGUR_API_KEY);
#$pvars = array('key' => $IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
#curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/gallery.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
$xmlsimple = new SimpleXMLElement($xml);
echo '<img height="180" src="';
echo $xmlsimple->links->original;
echo '">';
curl_close ($curl);
}
?>