错误的请求400将图像上传到imgur API

时间:2019-02-11 23:31:26

标签: php html imgur

我想将一些带有imgur-API的图片上传到imgur,但是我总是收到Error 400 Bad Request。有什么问题吗?

<?php
if (isset($_POST['uploadprofileimg'])) {
    $image = base64_encode(file_get_contents($_FILES['profileimg']['tmp_name']));
    $options = array('http'=>array(
            'method'=>"POST",
            'header'=>"Authorization: Bearer *MY_ACCESS_TOKEN*\n".
            "Content-Type: application/x-www-form-urlencoded",
            'content'=>$image
    ));
    $context = stream_context_create($options);
    $imgurURL = "https://api.imgur.com/3/image";
    $response = file_get_contents($imgurURL, false, $context);
}
?>

<h1>My Account</h1>
 <form action="upload-pb.php" method="post" enctype="multipart/form-data">
    Upload a profile image:
    <input type="file" name="profileimg">
    <input type="submit" name="uploadprofileimg" value="Upload Image">
</form>

1 个答案:

答案 0 :(得分:0)

查看/image here的端点,它需要参数image。您将其作为content传递,并且未正确编码为image。看here,我借用了如何使用stream_context_create / file_get_contents正确上传内容的方法:

<?php
 if (isset($_POST['uploadprofileimg'])) {
    $image = base64_encode(file_get_contents($_FILES['profileimg']['tmp_name']));
    $postdata = http_build_query(
        array(
            'image' => $image,
        )
    );
    $options = array('http'=>array(
            'method'=>"POST",
            'header'=>"Authorization: Bearer *MY_ACCESS_TOKEN*\n".
            "Content-Type: application/x-www-form-urlencoded",
            'content' => $postdata
    ));
    $context = stream_context_create($options);
    $imgurURL = "https://api.imgur.com/3/image";
    $response = file_get_contents($imgurURL, false, $context);