gpt4 book ai didi

php - 如何使用 PHP 将图像发送到 deviantsart Rest API

转载 作者:行者123 更新时间:2023-12-01 19:50:14 25 4
gpt4 key购买 nike

这里,其中一个响应 (#3) 告诉我们:

http://deviantsart.com has a public and easy to use API just HTTP POST the image to their domain and you will get a JSON with the URL

这是网址:

Are there any image hosting services with a public API?

唯一的说明基本上是

"Upload using our public REST API: POST http://deviantsart.com yourimage.jpg

JSON-Result:

{ "url" : "urltoimage" }"

很好,但是,我怎样才能使其可编程?

这是我的代码:

//the file was uploaded by a simple html form

if ($_POST) { //submit
$tmp = array_merge($_POST);

$r = new HttpRequest('http://deviantsart.com', HttpRequest::METH_POST);
$r->addPostFile($tmp['img']); //tmp has post vars
echo $r->getUrl();

try {
echo $r->send()->getBody();
exit();
} catch (HttpException $ex) {
echo $ex;
exit();
}
}

最后编辑:请不要关心我的代码,尝试用你自己的代码来解决。我只是想看看它是如何工作的。非常感谢!

最佳答案

是的,它应该很简单,但是......实现简单才是困难的;p

这是一个例子。我不使用或没有 PECL HttpRequest 类,因此我添加了 cURL 以防万一,如果您什么也没得到。您应该检查错误日志并启用错误报告。

<?php
//check is POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

//check image upload, your want to check for other things too like: is it an image?
if(isset($_FILES['img']['name'])){

//make filename for new file
$uploadfile = basename($_FILES['img']['name']);

//move the upload
if (move_uploaded_file($_FILES['img']['tmp_name'], $uploadfile)) {

/* HttpRequest - I dont use it, it should work but if like me,
its class not found, then this condition will revert to curl */
if(class_exists('HttpRequest')){
try {
$r = new HttpRequest('http://deviantsart.com', HttpRequest::METH_POST);
$r->addPostFile('file', $_SERVER['DOCUMENT_ROOT'].'/'.$uploadfile);

$resp = $r->send()->getBody();
} catch (HttpException $ex) {
$resp = $ex;
}
}
//simplez curl POST file
else{
$ch = curl_init('http://deviantsart.com');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'file'=>'@'.$_SERVER['DOCUMENT_ROOT'].'/'.$uploadfile,
));

$resp = curl_exec($ch);
}

//decode the json response
$resp = json_decode($resp, true);
}
}

}

//output the image from deviantsart
if(isset($resp['url'])){
echo '<img src="'.$resp['url'].'"/>';
}
?>
<form enctype="multipart/form-data" action="" method="POST">
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="img" type="file" />
<input type="submit" value="Send File" />
</form>

关于php - 如何使用 PHP 将图像发送到 deviantsart Rest API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24542600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com