Как создать новый файл с содержанием с помощью Ubuntu Один API и PHP

У меня есть некоторые проблемы, когда я пытаюсь создать новый файл с некоторым содержанием (или перезаписать содержание существующего) использование Ubuntu Один API и PHP.

Я могу легко создать и пустой файл или использование папки:

ПОМЕЩЕННЫЙ/api/file_storage/v1 / ~/path/to/volume/path/to/node

но я не понимаю ho для использования этой спецификации:

PUT /api/file_storage/v1/ + <directory.content_path> + '/' + filename.ext, or /api/file_storage/v1/ + <file.content_path>

PUT a new file, with content, in one action, or overwrite content of an existing file.
The body of the PUT request is the content of the file.
Note that you cannot PUT a new file with content and alter its attributes at the same time.
Note also that content_paths may not be rooted under the API root, and may change without warning, so they must be read from the API and not hardcoded.
(Note caveat above about CONTENT_ROOT being temporarily different.)

Я не отправляю целый код, но только строку, которая не работает:

$api_url = 'https://one.ubuntu.com/api/file_storage/v1/';
$filecontentent = "content of the txt file";

$oauth->fetch($api_url.'~/Ubuntu One.'.$filecontentent.'/try.txt', OAUTH_HTTP_METHOD_PUT);

Я не понимаю, как структурировать синтаксис. Можно ли помочь мне?

5
задан 29 July 2011 в 12:06

3 ответа

Наконец я нашел решение!

Было две проблемы:

  1. Теперь, поскольку теперь URL для содержания файлов не является URL API, но https://files.one.ubuntu.com

  2. перед путем к файлу необходимо поместить "содержание/путь к файлу"

Что-то вроде этого

OAuth-> выборка ('https://files.one.ubuntu.com/content / ~/Ubuntu%20One/prova.php');

2
ответ дан 23 November 2019 в 09:10

Проблема, которую Вы имеете, состоит в том, что для помещения файла с содержанием необходимо получить "content_path" каталога, Вы хотите сохранить файл в и затем ПОДВЕРГНУТЬ новый файл этому content_path. Посмотрите пример кода ниже, который создает папку ~/Ubuntu One/phptestfolder, получает его content_path и затем ПОМЕЩАЕТ файл foo.txt в той недавно созданной папке.

<?php
# Set up OAuth with the token details you've previously saved
$conskey = 'CCCCCC';
$conssec = 'SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS';
$token = 'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT';
$secret = 'ssssssssssssssssssssssssssssssssssssssssssssssssss';

$oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$oauth->enableSSLChecks();
$oauth->setToken($token,$secret);

# Create a folder in Ubuntu One.
# Folders are created by PUTting to the folder path with a PUT body of
# {"kind": "directory"} as explained at 
# https://one.ubuntu.com/developer/files/store_files/cloud/#put_apifile_storagev1pathtovolumepathtonode

$api_url = 'https://one.ubuntu.com/api/file_storage/v1/';
$oauth->fetch($api_url.'~/Ubuntu%20One/php-test-folder', '{"kind": "directory"}', OAUTH_HTTP_METHOD_PUT);
$response = json_decode($oauth->getLastResponse());
print_r($response);

# So now, we want to upload a file to that new folder. To do that, you need
# to get the directory content path. As explained at
# https://one.ubuntu.com/developer/files/store_files/cloud/#get_apifile_storagev1pathtovolumepathtonode
# "Note that a directory has a content_path. This means that you can PUT a new 
# file with content into that directory (see below) by PUTting to 
# CONTENT_ROOT + <directory.content-path> + '/' + filename.ext.
# CONTENT_ROOT is the root of the files API itself, /api/file_storage/v1/, but 
# temporarily it should be set to https://files.one.ubuntu.com. 
# (This note will be removed when this is fixed.)"
# So, we need the directory content path. This is returned in the output from
# the above statement ($oauth->getLastResponse). So, to put a file foo.txt
# with content "this is foo", the URL we need is:
# CONTENT_ROOT: https://files.one.ubuntu.com               +
# directory_content_path: $response['content_path']        +
# /: /                                                     +
# filename: foo.txt

# We want to urlencode the path (so that the space in "Ubuntu One", for example,
# becomes %20), but not any slashes therein (so the slashes don't become %2F).
# urlencode() encodes spaces as + so we need rawurlencode
$encpath = rawurlencode($response->content_path);
$encpath = str_replace("%2F", "/", $encpath);

$put_file_url = "https://files.one.ubuntu.com" . $encpath . "/" . "foo.txt";
$oauth->fetch($put_file_url, "this is foo", OAUTH_HTTP_METHOD_PUT, array('Content-Type'=>'application/json'));
$response = json_decode($oauth->getLastResponse());
print_r($response);

?>
4
ответ дан 23 November 2019 в 09:10
$oauth->fetch($api_url.'~/Ubuntu One.'.$filecontentent.'/try.txt', OAUTH_HTTP_METHOD_PUT);

Я думаю, что существует несколько ошибок:

  • OAUTH_HTTP_METHOD_PUT является третьим аргументом не второе для OAuth-> выборка ()
  • /Ubuntu One.' возможно, вместо. Вы хотели/?
  • содержание файла, я думаю, что это должен быть второй аргумент

таким образом, по моему скромному мнению, исправленная строка:

$oauth->fetch($api_url.'~/Ubuntu One/try.txt', $filecontentent, OAUTH_HTTP_METHOD_PUT);

(возможно, Вы хотите к corrent даже $filecontentent кому: $filecontent)

1
ответ дан 23 November 2019 в 09:10

Другие вопросы по тегам:

Похожие вопросы: