Timeline.attachments: insert
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Cần phải uỷ quyền
Thêm tệp đính kèm mới vào mục trong dòng thời gian.
Xem ví dụ.
Phương thức này hỗ trợ URI /upload và chấp nhận nội dung nghe nhìn đã tải lên có các đặc điểm sau:
- Kích thước tệp tối đa: 10 MB
- Các loại MIME nội dung đa phương tiện được chấp nhận:
image/*
,
audio/*
,
video/*
Yêu cầu
Yêu cầu HTTP
POST https://www.googleapis.com/upload/mirror/v1/timeline/itemId/attachments
Tham số
Tên thông số |
Giá trị |
Mô tả |
Tham số đường dẫn |
itemId |
string |
Mã của mục dòng thời gian có chứa tệp đính kèm.
|
Tham số truy vấn bắt buộc |
uploadType |
string |
Loại yêu cầu tải lên đối với URI /upload.
Các giá trị được chấp nhận là:
media – Tải lên đơn giản. Tải dữ liệu nội dung nghe nhìn lên.
resumable – Tải lên tiếp nối. Tải tệp lên theo cách tiếp tục, sử dụng một chuỗi ít nhất hai yêu cầu.
|
Ủy quyền
Yêu cầu này cần có sự cho phép có phạm vi sau (đọc thêm về quy trình xác thực và uỷ quyền).
Phạm vi |
https://www.googleapis.com/auth/glass.timeline |
Nội dung yêu cầu
Đừng cung cấp nội dung yêu cầu bằng phương thức này.
Ví dụ
Lưu ý: Các đoạn mã mẫu của phương thức này không phải là ví dụ cho mọi ngôn ngữ lập trình được hỗ trợ (xem trang thông tin về các thư viện dùng cho ứng dụng để biết danh sách các ngôn ngữ được hỗ trợ).
Java
Dùng thư viện ứng dụng Java.
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.model.Attachment;
import java.io.IOException;
import java.io.InputStream;
public class MyClass {
// ...
/**
* Insert a new attachment for the specified timeline item.
*
* @param service Authorized Mirror service.
* @param itemId ID of the timeline item to insert attachment for.
* @param contentType Attachment's content type (supported content types are
* "image/*", "video/*", "audio/*").
* @param attachment Attachment to insert.
* @return Attachment's metadata on success, {@code null} otherwise.
*/
public static Attachment insertAttachment(Mirror service, String itemId, String contentType,
InputStream attachment) {
try {
InputStreamContent mediaContent = new InputStreamContent(contentType, attachment);
return service.timeline().attachments().insert(itemId, mediaContent).execute();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
}
// ...
}
.NET
Dùng thư viện ứng dụng.NET.
using System;
using Google.Apis.Mirror.v1;
using Google.Apis.Mirror.v1.Data;
using System.IO;
public class MyClass {
// ...
/// <summary>
/// Insert a new attachment for the specified timeline item.
/// </summary>
/// <param name="service">Authorized Mirror service.</param>
/// <param name="itemId">ID of the timeline item to insert attachment for.</param>
/// <param name="contentType">
/// Attachment's content type (supported content types are "image/*", "video/*", "audio/*").
/// </param>
/// <param name="stream">Attachment to insert.</param>
/// <returns>Attachment's metadata on success, null otherwise.</returns>
public static Attachment InsertAttachment(
MirrorService service, String itemId, String contentType, Stream stream) {
try {
TimelineResource.AttachmentsResource.InsertMediaUpload request =
service.Timeline.Attachments.Insert(itemId, stream, contentType);
request.Upload();
return request.ResponseBody;
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
// ...
}
PHP
Dùng thư viện ứng dụng PHP.
/**
* Insert a new Timeline Item in the user's glass with an optional
* notification and attachment.
*
* @param Google_MirrorService $service Authorized Mirror service.
* @param string $text Timeline Item's text.
* @param string $contentType Optional attachment's content type (supported
* content types are "image/*", "video/*"
* and "audio/*").
* @param string $attachment Optional attachment content.
* @param string $notificationLevel Optional notification level,
* supported values are {@code null}
* and "AUDIO_ONLY".
* @return Google_TimelineItem Inserted Timeline Item on success, otherwise.
*/
function insertAttachment($service, $itemId, $contentType, $attachment) {
try {
$params = array(
'data' => $attachment,
'mimeType' => $contentType,
'uploadType' => 'media');
return $service->timeline_attachments->insert($itemId, $params);
} catch (Exception $e) {
print 'An error ocurred: ' . $e->getMessage();
return null;
}
}
Python
Dùng thư viện ứng dụng Python.
from apiclient import errors
# ...
def insert_attachment(service, item_id, content_type, attachment):
"""Insert an new attachment for the specified timeline item.
Args:
service: Authorized Mirror service.
item_id: ID of the timeline item to insert attachment for.
content_type: Attachment's content type (supported content types are
'image/*', 'video/*' and 'audio/*').
attachment: Attachment to insert as data string.
Returns:
Attachment's metadata on success, None otherwise.
"""
try:
media_body = MediaIoBaseUpload(
io.BytesIO(attachment), mimetype=content_type, resumable=True)
return service.timeline().attachments().insert(
itemId=item_id, media_body=media_body).execute()
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
Ruby
Dùng thư viện ứng dụng Ruby.
##
# Insert an new attachment for the specified timeline item.
#
# @param [Google::APIClient] client
# Authorized client instance.
# @param [String] item_id
# ID of the timeline item to insert attachment for.
# @param [String] content_type
# Attachment's content type (supported content types are 'image/*', 'video/*'
# and 'audio/*').
# @param [String] filename
# Attachment's filename.
# @return [Google::APIClient::Schema::Mirror::V1::Attachment]
# Attachment's metadata on success, nil otherwise.
def insert_attachment(client, item_id, content_type, filename)
mirror = client.discovered_api('mirror', 'v1')
media = Google::APIClient::UploadIO.new(filename, content_type)
result = client.execute(
:api_method => mirror.timeline.attachments.insert,
:media => media,
:parameters => {
'itemId' => item_id,
'uploadType' => 'resumable',
'alt' => 'json'})
if result.success?
return result.data
else
puts "An error occurred: #{result.data['error']['message']}"
end
end
HTTP thô
Không sử dụng thư viện ứng dụng.
POST /upload/mirror/v1/timeline/timeline item id/attachments?uploadType=media HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer auth token
Content-Type: media content type
Content-Length: media content length
media bytes
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2024-08-22 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2024-08-22 UTC."],[[["\u003cp\u003eAdds a new image, audio, or video attachment (up to 10MB) to an existing timeline item.\u003c/p\u003e\n"],["\u003cp\u003eRequires authorization with the \u003ccode\u003ehttps://www.googleapis.com/auth/glass.timeline\u003c/code\u003e scope.\u003c/p\u003e\n"],["\u003cp\u003eThe request is made to the \u003ccode\u003e/upload/mirror/v1/timeline/itemId/attachments\u003c/code\u003e endpoint using the \u003ccode\u003ePOST\u003c/code\u003e method.\u003c/p\u003e\n"],["\u003cp\u003eSupports both \u003ccode\u003emedia\u003c/code\u003e and \u003ccode\u003eresumable\u003c/code\u003e upload types.\u003c/p\u003e\n"],["\u003cp\u003eProvides code examples in Java, .NET, PHP, Python, and Ruby.\u003c/p\u003e\n"]]],[],null,["# Timeline.attachments: insert\n\n**Requires [authorization](#auth)**\n\nAdds a new attachment to a timeline item.\n[See an example](#examples).\n\nThis method supports an **/upload** URI and accepts uploaded media with the following characteristics:\n\n- **Maximum file size:** 10MB\n- **Accepted Media MIME types:** `image/*` , `audio/*` , `video/*`\n\nRequest\n-------\n\n### HTTP request\n\n```\nPOST https://www.googleapis.com/upload/mirror/v1/timeline/itemId/attachments\n```\n\n### Parameters\n\n| Parameter name | Value | Description |\n|----------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| **Path parameters** |||\n| `itemId` | `string` | The ID of the timeline item the attachment belongs to. |\n| **Required query parameters** |||\n| `uploadType` | `string` | The type of upload request to the **/upload** URI. Acceptable values are: - `media` - [Simple upload](/glass/media-upload#simple). Upload the media data. - `resumable` - [Resumable upload](/glass/media-upload#resumable). Upload the file in a resumable fashion, using a series of at least two requests. |\n\n### Authorization\n\nThis request requires authorization with the following scope ([read more about authentication and authorization](/glass/authorization)).\n\n| Scope |\n|--------------------------------------------------|\n| `https://www.googleapis.com/auth/glass.timeline` |\n\n### Request body\n\nDo not supply a request body with this method.\n\nResponse\n--------\n\nIf successful, this method returns a [Timeline.attachments resource](/glass/v1/reference/timeline/attachments#resource) in the response body.\n\nExamples\n--------\n\n**Note:** The code examples available for this method do not represent all supported programming languages (see the [client libraries page](/glass/tools-downloads/client-libraries) for a list of supported languages). \n\n### Java\n\nUses the [Java client library](/glass/tools-downloads/client-libraries). \n\n```java\nimport com.google.api.client.http.InputStreamContent;\nimport com.google.api.services.mirror.Mirror;\nimport com.google.api.services.mirror.model.Attachment;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\npublic class MyClass {\n // ...\n\n /**\n * Insert a new attachment for the specified timeline item.\n * \n * @param service Authorized Mirror service.\n * @param itemId ID of the timeline item to insert attachment for.\n * @param contentType Attachment's content type (supported content types are\n * \"image/*\", \"video/*\", \"audio/*\").\n * @param attachment Attachment to insert.\n * @return Attachment's metadata on success, {@code null} otherwise.\n */\n public static Attachment insertAttachment(Mirror service, String itemId, String contentType,\n InputStream attachment) {\n try {\n InputStreamContent mediaContent = new InputStreamContent(contentType, attachment);\n return service.timeline().attachments().insert(itemId, mediaContent).execute();\n } catch (IOException e) {\n // An error occurred.\n e.printStackTrace();\n return null;\n }\n }\n\n // ...\n}\n```\n\n### .NET\n\nUses the [.NET client library](/glass/tools-downloads/client-libraries). \n\n```gdscript\nusing System;\nusing Google.Apis.Mirror.v1;\nusing Google.Apis.Mirror.v1.Data;\nusing System.IO;\n\npublic class MyClass {\n // ...\n\n /// \u003csummary\u003e\n /// Insert a new attachment for the specified timeline item.\n /// \u003c/summary\u003e\n /// \u003cparam name=\"service\"\u003eAuthorized Mirror service.\u003c/param\u003e\n /// \u003cparam name=\"itemId\"\u003eID of the timeline item to insert attachment for.\u003c/param\u003e\n /// \u003cparam name=\"contentType\"\u003e\n /// Attachment's content type (supported content types are \"image/*\", \"video/*\", \"audio/*\").\n /// \u003c/param\u003e\n /// \u003cparam name=\"stream\"\u003eAttachment to insert.\u003c/param\u003e\n /// \u003creturns\u003eAttachment's metadata on success, null otherwise.\u003c/returns\u003e\n public static Attachment InsertAttachment(\n MirrorService service, String itemId, String contentType, Stream stream) {\n try {\n TimelineResource.AttachmentsResource.InsertMediaUpload request = \n service.Timeline.Attachments.Insert(itemId, stream, contentType);\n request.Upload();\n return request.ResponseBody;\n } catch (Exception e) {\n Console.WriteLine(\"An error occurred: \" + e.Message);\n return null;\n }\n }\n\n // ...\n}\n```\n\n### PHP\n\nUses the [PHP client library](/glass/tools-downloads/client-libraries). \n\n```php\n/**\n * Insert a new Timeline Item in the user's glass with an optional\n * notification and attachment.\n *\n * @param Google_MirrorService $service Authorized Mirror service.\n * @param string $text Timeline Item's text.\n * @param string $contentType Optional attachment's content type (supported\n * content types are \"image/*\", \"video/*\"\n * and \"audio/*\").\n * @param string $attachment Optional attachment content.\n * @param string $notificationLevel Optional notification level,\n * supported values are {@code null}\n * and \"AUDIO_ONLY\".\n * @return Google_TimelineItem Inserted Timeline Item on success, otherwise.\n */\nfunction insertAttachment($service, $itemId, $contentType, $attachment) {\n try {\n $params = array(\n 'data' =\u003e $attachment,\n 'mimeType' =\u003e $contentType,\n 'uploadType' =\u003e 'media');\n return $service-\u003etimeline_attachments-\u003einsert($itemId, $params);\n } catch (Exception $e) {\n print 'An error ocurred: ' . $e-\u003egetMessage();\n return null;\n }\n}\n```\n\n### Python\n\nUses the [Python client library](/glass/tools-downloads/client-libraries). \n\n```python\nfrom apiclient import errors\n# ...\n\ndef insert_attachment(service, item_id, content_type, attachment):\n \"\"\"Insert an new attachment for the specified timeline item.\n\n Args:\n service: Authorized Mirror service.\n item_id: ID of the timeline item to insert attachment for.\n content_type: Attachment's content type (supported content types are\n 'image/*', 'video/*' and 'audio/*').\n attachment: Attachment to insert as data string.\n Returns:\n Attachment's metadata on success, None otherwise.\n \"\"\"\n try:\n media_body = MediaIoBaseUpload(\n io.BytesIO(attachment), mimetype=content_type, resumable=True)\n return service.timeline().attachments().insert(\n itemId=item_id, media_body=media_body).execute()\n except errors.HttpError, error:\n print 'An error occurred: %s' % error\n return None\n```\n\n### Ruby\n\nUses the [Ruby client library](/glass/tools-downloads/client-libraries). \n\n```ruby\n##\n# Insert an new attachment for the specified timeline item.\n#\n# @param [Google::APIClient] client\n# Authorized client instance.\n# @param [String] item_id\n# ID of the timeline item to insert attachment for.\n# @param [String] content_type\n# Attachment's content type (supported content types are 'image/*', 'video/*'\n# and 'audio/*').\n# @param [String] filename\n# Attachment's filename.\n# @return [Google::APIClient::Schema::Mirror::V1::Attachment]\n# Attachment's metadata on success, nil otherwise.\ndef insert_attachment(client, item_id, content_type, filename)\n mirror = client.discovered_api('mirror', 'v1')\n media = Google::APIClient::UploadIO.new(filename, content_type)\n result = client.execute(\n :api_method =\u003e mirror.timeline.attachments.insert,\n :media =\u003e media,\n :parameters =\u003e {\n 'itemId' =\u003e item_id,\n 'uploadType' =\u003e 'resumable',\n 'alt' =\u003e 'json'})\n if result.success?\n return result.data\n else\n puts \"An error occurred: #{result.data['error']['message']}\"\n end\nend\n```\n\n### Raw HTTP\n\nDoes not use a client library. \n\n```gdscript\nPOST /upload/mirror/v1/timeline/timeline item id/attachments?uploadType=media HTTP/1.1\nHost: www.googleapis.com\nAuthorization: Bearer auth token\nContent-Type: media content type\nContent-Length: media content length\n\nmedia bytes\n```"]]