Имя: Пароль:
IT
Веб-мастеринг
Кто может подсказать по Amazon S3 ? Скрипт на PHP
,
0 D_Pavel
 
10.08.12
06:23
Никак не могу сделать загрузку файлов из браузера на PHP. Ошибку не выдает, но и файл не загружает.

<?php
require_once '../sdk.class.php';
require_once '../extensions/s3browserupload.class.php';

$upload = new S3BrowserUpload();

// Generate the parameters for the upload.
$html_parameters = $upload->generate_upload_parameters('fotk');
?>

<form action="<?= $html_parameters['form']['action'] ?>" method="<?= $html_parameters['form']['method'] ?>" enctype="<?= $html_parameters['form']['enctype'] ?>">

   <input type="file" name="file">

   <? foreach ($html_parameters['inputs'] as $name => $value): ?>
   <input type="input" name="<?= $name; ?>" value="<?= $value; ?>">
   <? endforeach; ?>

   <input type="submit" name="upload" value="Upload">
</form>
1 goodzone
 
10.08.12
06:25
поставь трай, отлови ексцепшн!
2 Андрюха
 
10.08.12
06:34
опять вы?
3 goodzone
 
10.08.12
06:38
(2) и вы опять!
4 D_Pavel
 
10.08.12
08:04
Up!
5 D_Pavel
 
10.08.12
08:08
Нашел и исправил одну ошибку, добавил "http://"

<form action="http://<?= $html_parameters['form']['action'] ?>" method="<?= $html_parameters['form']['method'] ?>" enctype="<?= $html_parameters['form']['enctype'] ?>">

выдает ответ страницу с 400 ошибкой после отправки данных из формы. При обновлении этой страницы без отправки данных формы возвращается xml.
6 D_Pavel
 
10.08.12
08:10
Вот ссылка на этот файл: http://pavel.cc/s3/_samples/proba.php
7 goodzone
 
10.08.12
08:12
Берешь firefox+firebug. Включаешь firebug. Идешь на свою страницу, и смотришь POST, GET, и ответы. Анализируешь. Выявляешь ошибку, - исправляешь! Все :)
8 D_Pavel
 
10.08.12
08:13
А, оказывается что IE не отображает страницу так как она слишком короткая. Открыл в гугале чроме, прочитал ответ сервера.
9 D_Pavel
 
10.08.12
08:14
(7) не все так просто. Я не очень понимаю какие должны быть запросы правильные.
10 goodzone
 
10.08.12
08:14
Мне IE для отладки Java - по приколу. А в остальном - его нах.
11 goodzone
 
10.08.12
08:14
Javascript-а я хотел сказать
12 D_Pavel
 
10.08.12
08:16
Он все равно нужен для проверки верстки. Отказаться не могу от IE
13 slnes
 
10.08.12
08:26
покажи функцию generate_upload_parameters в классе S3BrowserUpload()
14 slnes
 
10.08.12
08:28
думаю она в файле /extensions/s3browserupload.class.php
15 D_Pavel
 
10.08.12
08:37
(13)
16 D_Pavel
 
10.08.12
08:37
public function generate_upload_parameters($bucket, $expires = '+1 hour', $opt = null)
   {
       if (!$opt) $opt = array();

       // Policy document
       $policy = array(
           'conditions' => array(
               array('bucket' => $bucket),
           )
       );

       // Basic form
       $form = array();
       $form['form'] = array(
           'action' => $bucket . '.s3.amazonaws.com',
           'method' => 'POST',
           'enctype' => 'multipart/form-data'
       );

       // Inputs
       $form['inputs'] = array(
           'AWSAccessKeyId' => $this->key
       );

       // Expires
       if ($expires)
       {
           if (is_numeric($expires))
           {
               $expires = gmdate('j M Y, g:i a Z', (integer) $expires);
           }

           $expires = $this->util->convert_date_to_iso8601($expires);
           $policy['expiration'] = (string) $expires;
       }

       // Default values
       if (!isset($opt['key']))
       {
           $opt['key'] = '${filename}';
       }

       // Success Action Status
       if (isset($opt['success_action_status']) && !empty($opt['success_action_status']))
       {
           $form['inputs']['success_action_status'] = (string) $opt['success_action_status'];
           $policy['conditions'][] = array(
               'success_action_status' => (string) $opt['success_action_status']
           );
           unset($opt['success_action_status']);
       }

       // Other parameters
       foreach ($opt as $param_key => $param_value)
       {
           if ($param_value[0] === '^')
           {
               $form['inputs'][$param_key] = substr((string) $param_value, 1);
               $param_value = preg_replace('/\$\{(\w*)\}/', '', (string) $param_value);
               $policy['conditions'][] = array('starts-with', '$' . $param_key, (substr((string) $param_value, 1) ? substr((string) $param_value, 1) : ''));
           }
           else
           {
               $form['inputs'][$param_key] = (string) $param_value;
               $policy['conditions'][] = array(
                   $param_key => (string) $param_value
               );
           }
       }

       // Add policy
       $json_policy = json_encode($policy);
       $json_policy_b64 = base64_encode($json_policy);
       $form['inputs']['policy'] = $json_policy_b64;
       $form['metadata']['json_policy'] = $json_policy;

       // Add signature
       $form['inputs']['signature'] = base64_encode(hash_hmac('sha1', $json_policy_b64, $this->secret_key, true));

       return $form;
   }


   /*%******************************************************************************************%*/
   // HELPERS

   /**
    * Returns the protocol of the web page that this script is currently running on. This method only works
    * correctly when run from a publicly-accessible web page.
    */
   public static function protocol()
   {
       return (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on') ? 'https://' : 'http://';
   }

   /**
    * Returns the domain (and port) of the web page that this script is currently running on. This method
    * only works correctly when run from a publicly-accessible web page.
    */
   public static function domain()
   {
       if (isset($_SERVER['SERVER_NAME']) && isset($_SERVER['SERVER_PORT']))
       {
           return $_SERVER['SERVER_NAME'] . ((integer) $_SERVER['SERVER_PORT'] === 80 ? '' : ':' . $_SERVER['SERVER_PORT']);
       }

       return null;
   }

   /**
    * Returns the URI of the web page that this script is currently running on. This method only works
    * correctly when run from a publicly-accessible web page.
    */
   public static function current_uri()
   {
       if (isset($_SERVER['REQUEST_URI']))
       {
           $uri = self::protocol();
           $uri .= self::domain();
           $uri .= $_SERVER['REQUEST_URI'];
           return $uri;
       }

       return null;
   }
}
17 D_Pavel
 
10.08.12
08:38
Вот такая ошибка получается:

<Error>
<Code>InvalidPolicyDocument</Code>
<Message>
Invalid Policy: Invalid Simple-Condition: value must be a string.
</Message>
<RequestId>209DFC1FC1C7E9C6</RequestId>
<HostId>
y5qV2+olejiBpJpABMx2L24ic5uHRNiLyl/G+pYYWR0ZNBgg4dDl5Bbga3UXSLUg
</HostId>
</Error>
18 D_Pavel
 
10.08.12
09:06
Up
19 slnes
 
10.08.12
09:34
убери "hppt//:", или прочитай тему PHP-Строки
s3.amazonaws.com должен днать что ты передаешь POST с именем File
20 D_Pavel
 
10.08.12
09:43
(19) Зачем убирать hppt:// ????
<input type="file" name="file">  перенес после цикла.
21 Андрюха
 
10.08.12
10:07
(20) Затем, что правильно писать hTTp а не hPPt
22 D_Pavel
 
10.08.12
10:31
(21) Где у меня написано hPPt и откуда его убрать? Не сочиняй
23 slnes
 
10.08.12
11:31
в (19) http:// я имел ввиду
24 D_Pavel
 
10.08.12
12:11
Я тоже. Не нужно его убирать.
25 D_Pavel
 
13.08.12
06:00
Разобрался. Оказывается скрипт из сэмплов не рабочий.
Написал свой по мануалу, работает!
Оптимист верит, что мы живем в лучшем из миров. Пессимист боится, что так оно и есть.