Загрузка изображений в облачные файлы с помощью PHP

Я пытаюсь загрузить файл в облачный файл стеллажа, используя следующий код:

Загрузить.html

<form action="upload.php" enctype="multipart/form-data" method="POST">
    File: 
    <input name="upload" type="file" /> 
    <input name="submit" type="submit" value="Upload To Rackspace!" />
</form>

Загрузить.php

<?php

// include the API
require('cloudfiles.php');

// cloud info
$username = ""; // username
$key = ""; // api key

// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);

// Get the container we want to use
$container = $conn->get_container('resumetune');

// store file information
$localfile = $_FILES['upload']['tmp_name'];
$filename  = $_FILES['upload']['name'];

// upload file to Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($localfile);

?>

Теперь я получаю сообщение об ошибке:

Неустранимая ошибка: необработанное исключение «BadContentTypeException» с сообщением «Требуемый тип контента не установлен» в C:\xampp\htdocs\rackspace\cloudfiles.php:1645 Трассировка стека: #0 C:\xampp\htdocs\rackspace\cloudfiles.php (1962): CF_Object->_guess_content_type('C:\xampp\tmp\ph...') #1 C:\xampp\htdocs\rackspace\upload.php(24): CF_Object->load_from_filename('C:\ xampp\tmp\ph...') #2 {main} добавлено в C:\xampp\htdocs\rackspace\cloudfiles.php в строке 1645

Так что у кого-нибудь есть идеи по этому поводу? заранее спасибо.


person M.M.H.Masud    schedule 20.02.2010    source источник


Ответы (5)


глядя на http://github.com/rackspace/php-cloudfiles/blob/master/cloudfiles.php в функции _guess_content_type() он ищет Content-type и не находит его. Либо вам нужно добавить больше информации в ваш /share/magic, либо вы, вероятно, можете установить Content-type перед вызовом load_from_filename, если вы знаете, что такое тип контента.

person John Boker    schedule 20.02.2010
comment
спасибо, я понял .. сразу после публикации вопросов. в любом случае, спасибо - person M.M.H.Masud; 20.02.2010

Вот исправление, если у вас нет доступных функций mime или FileInfo:

function _guess_content_type($handle) {

    $ext = ".".end(explode(".", $handle));
    switch($ext)
    {
        case 'jpg': $this->content_type = "image/jpeg"; break;
        case 'gif': $this->content_type = "image/gif"; break;
        case 'png': $this->content_type = "image/png"; break;
        default: $this->content_type = "image/jpeg"; break;
    }

    if ($this->content_type)
        return;

    if (function_exists("finfo_open")) {
        $local_magic = dirname(__FILE__) . "/share/magic";
        $finfo = @finfo_open(FILEINFO_MIME, $local_magic);

        if (!$finfo) 
            $finfo = @finfo_open(FILEINFO_MIME);

        if ($finfo) {

            if (is_file((string)$handle))
                $ct = @finfo_file($finfo, $handle);
            else 
                $ct = @finfo_buffer($finfo, $handle);

            /* PHP 5.3 fileinfo display extra information like
               charset so we remove everything after the ; since
               we are not into that stuff */
            if ($ct) {
                $extra_content_type_info = strpos($ct, "; ");
                if ($extra_content_type_info)
                    $ct = substr($ct, 0, $extra_content_type_info);
            }

            if ($ct && $ct != 'application/octet-stream')
                $this->content_type = $ct;

            @finfo_close($finfo);
        }
    }

    if (!$this->content_type && (string)is_file($handle) && function_exists("mime_content_type")) {
        $this->content_type = mime_content_type($handle);
    }

    if (!$this->content_type) {
        throw new BadContentTypeException("Required Content-Type not set");
    }
    return True;
}
person Chris Bake    schedule 07.07.2010
comment
Хороший ответ, решил мою проблему! - person Andrew G. Johnson; 31.07.2010
comment
Идеально. Спас меня от головной боли! - person Ignas; 10.12.2012

Если у вас не включено расширение FileInfo (включено по умолчанию, начиная с PHP 5.30). Я предлагаю вам проверить, доступна ли функция mime_content_type().

Кажется, что если у вас нет ни того, ни другого, Content-Type не может быть обнаружен. Если ни один из них сейчас недоступен, я получу FileInfo.

person Kaj Ström    schedule 20.02.2010

Я нашел решение Криса Бэйка полезным. Мне нужно было поставить "." перед каждым расширением ниже.

$ext = ".".end(explode(".", $handle));
switch($ext)
{
    case '.jpg': $this->content_type = "image/jpeg"; break;
    case '.gif': $this->content_type = "image/gif"; break;
    case '.png': $this->content_type = "image/png"; break;
    default: $this->content_type = "image/jpeg"; break;
}
person Brent    schedule 13.01.2013

Вы также можете рассмотреть возможность использования более нового официального Rackspace PHP SDK. Вот пример кода для создания объекта.

person Everett Toews    schedule 13.01.2013