미디어 항목 업로드는 두 단계로 이루어집니다.
- 업로드 엔드포인트를 사용하여 미디어 파일의 바이트를 Google 서버에 업로드합니다. 이렇게 하면 업로드된 바이트를 식별하는 업로드 토큰이 반환됩니다.
- 업로드 토큰과 함께 batchCreate 호출을 사용하여 사용자의 Google 포토 계정에서 미디어 항목을 만듭니다.
이 단계에서는 단일 미디어 항목을 업로드하는 프로세스를 간략하게 설명합니다. 여러 미디어 항목을 업로드하는 경우 (프로덕션 애플리케이션에 있을 가능성이 매우 높음) 업로드 권장사항을 검토하여 업로드 효율을 개선하세요.
시작하기 전에
필수 승인 범위
사용자의 라이브러리 또는 앨범에 미디어 항목을 업로드하려면 photoslibrary.appendonly
또는 photoslibrary
범위가 필요합니다.
photoslibrary.sharing
범위를 사용하여 미디어 항목을 만들 수도 있습니다. photoslibrary.sharing
범위로 항목을 만들려면 먼저 앨범을 만들고 shareAlbum
를 사용하여 공유됨으로 표시해야 합니다. 그런 다음 앨범에서 사용자와 공유할 미디어 항목을 만들 수 있습니다. 사용자의 라이브러리 또는 앱이 공유하지 않은 앨범에서는 항목을 직접 만들 수 없습니다.
앨범을 나열할 때 isWriteable
속성은 애플리케이션에 특정 앨범에 미디어를 만들 수 있는 액세스 권한이 있는지 여부를 나타냅니다.
허용되는 파일 형식 및 크기
아래 표에 나열된 파일 형식을 업로드할 수 있습니다.
미디어 유형 | 허용되는 파일 형식 | 최대 파일 크기 |
---|---|---|
사진 | AVIF, BMP, GIF, HEIC, ICO, JPG, PNG, TIFF, WEBP, 일부 RAW 파일 | 200MB |
동영상 | 3GP, 3G2, ASF, AVI, DIVX, M2T, M2TS, M4V, MKV, MMV, MOD, MOV, MP4, MPG, MTS, TOD, WMV | 20GB |
1단계: 바이트 업로드
업로드 요청을 사용하여 Google에 바이트를 업로드합니다. 업로드 요청이 성공하면 원시 텍스트 문자열 형식으로 업로드 토큰이 반환됩니다. 이러한 업로드 토큰을 사용하여 batchCreate
호출로 미디어 항목을 만듭니다.
REST
POST 요청 헤더에 다음 필드를 포함합니다.
헤더 필드 | |
---|---|
Content-type |
application/octet-stream 로 설정합니다. |
X-Goog-Upload-Content-Type |
권장사항입니다. 업로드하는 바이트의 MIME 유형으로 설정합니다.
일반적인 MIME 유형에는 image/jpeg , image/png , image/gif 가 있습니다.
|
X-Goog-Upload-Protocol |
raw 로 설정합니다. |
다음은 POST 요청 헤더입니다.
POST https://photoslibrary.googleapis.com/v1/uploads Authorization: Bearer oauth2-token Content-type: application/octet-stream X-Goog-Upload-Content-Type: mime-type X-Goog-Upload-Protocol: raw
요청 본문에 파일의 바이너리를 포함합니다.
media-binary-data
이 POST 요청이 성공하면 원시 텍스트 문자열 형식의 업로드 토큰이 응답 본문으로 반환됩니다. 미디어 항목을 만들려면 batchCreate
호출에 다음 텍스트 문자열을 사용하세요.
upload-token
Java
// Open the file and automatically close it after upload try (RandomAccessFile file = new RandomAccessFile(pathToFile, "r")) { // Create a new upload request UploadMediaItemRequest uploadRequest = UploadMediaItemRequest.newBuilder() // The media type (e.g. "image/png") .setMimeType(mimeType) // The file to upload .setDataFile(file) .build(); // Upload and capture the response UploadMediaItemResponse uploadResponse = photosLibraryClient.uploadMediaItem(uploadRequest); if (uploadResponse.getError().isPresent()) { // If the upload results in an error, handle it Error error = uploadResponse.getError().get(); } else { // If the upload is successful, get the uploadToken String uploadToken = uploadResponse.getUploadToken().get(); // Use this upload token to create a media item } } catch (ApiException e) { // Handle error } catch (IOException e) { // Error accessing the local file }
2,399필리핀
try { // Create a new upload request by opening the file // and specifying the media type (e.g. "image/png") $uploadToken = $photosLibraryClient->upload(file_get_contents($localFilePath), null, $mimeType); } catch (\GuzzleHttp\Exception\GuzzleException $e) { // Handle error }
권장되는 이미지 파일 크기는 50MB 미만입니다. 크기가 50MB를 초과하는 파일은 성능 문제가 발생하기 쉽습니다.
Google 포토 라이브러리 API는 재개 가능한 업로드를 지원합니다. 재개 가능한 업로드를 사용하면 미디어 파일을 여러 섹션으로 분할하고 한 번에 하나의 섹션을 업로드할 수 있습니다.
2단계: 미디어 항목 만들기
미디어 파일의 바이트를 업로드한 후 업로드 토큰을 사용하여 Google 포토에서 미디어 항목으로 만들 수 있습니다. 업로드 토큰은 생성 후 1일 동안 유효합니다. 미디어 항목은 항상 사용자의 라이브러리에 추가됩니다. 미디어 항목은 앱에서 만든 앨범에만 추가할 수 있습니다. 자세한 내용은 승인 범위를 참고하세요.
새 미디어 항목을 만들려면 newMediaItems
목록을 지정하여 mediaItems.batchCreate
를 호출합니다. 각 newMediaItem
에는 simpleMediaItem
내에 지정된 업로드 토큰과 사용자에게 표시되는 설명(선택사항)이 포함됩니다.
설명 필드는 1,000자(영문 기준)로 제한되며 사용자가 만든 의미 있는 텍스트만 포함해야 합니다. 예: '공원 여행' 또는 '휴일 저녁 식사' 파일 이름, 프로그래매틱 태그 또는 기타 자동 생성된 텍스트와 같은 메타데이터를 포함하지 마세요.
최상의 성능을 얻으려면 한 번의 호출에 여러 미디어 항목을 포함하여 mediaItems.batchCreate
호출 수를 줄이세요. 항상 이전 요청이 완료될 때까지 기다린 후에 동일한 사용자를 후속 호출하세요.
설명 및 해당 업로드 토큰을 지정하여 사용자의 라이브러리에 단일 미디어 항목 또는 여러 미디어 항목을 만들 수 있습니다.
REST
다음은 POST 요청 헤더입니다.
POST https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate Content-type: application/json Authorization: Bearer oauth2-token
요청 본문은 newMediaItems
목록을 지정해야 합니다.
{ "newMediaItems": [ { "description": "item-description", "simpleMediaItem": { "fileName": "filename", "uploadToken": "upload-token" } } , ... ] }
Java
try { // Create a NewMediaItem with the following components: // - uploadToken obtained from the previous upload request // - filename that will be shown to the user in Google Photos // - description that will be shown to the user in Google Photos NewMediaItem newMediaItem = NewMediaItemFactory .createNewMediaItem(uploadToken, fileName, itemDescription); List<NewMediaItem> newItems = Arrays.asList(newMediaItem); BatchCreateMediaItemsResponse response = photosLibraryClient.batchCreateMediaItems(newItems); for (NewMediaItemResult itemsResponse : response.getNewMediaItemResultsList()) { Status status = itemsResponse.getStatus(); if (status.getCode() == Code.OK_VALUE) { // The item is successfully created in the user's library MediaItem createdItem = itemsResponse.getMediaItem(); } else { // The item could not be created. Check the status and try again } } } catch (ApiException e) { // Handle error }
2,399필리핀
try { $newMediaItems = []; // Create a NewMediaItem with the following components: // - uploadToken obtained from the previous upload request // - filename that will be shown to the user in Google Photos // - description that will be shown to the user in Google Photos $newMediaItems[0] = PhotosLibraryResourceFactory::newMediaItemWithDescriptionAndFileName( $uploadToken, $itemDescription, $fileName); $response = $photosLibraryClient->batchCreateMediaItems($newMediaItems); foreach ($response->getNewMediaItemResults() as $itemResult) { $status = $itemResult->getStatus(); if ($status->getCode() != Code::OK) { // Error while creating the item. } } } catch (\Google\ApiCore\ApiException $e) { // Handle error }
앨범 id
를 지정하여 라이브러리와 앨범에 미디어 항목을 추가할 수 있습니다. 자세한 내용은 앨범 만들기를 참고하세요.
각 앨범은 최대 20,000개의 미디어 항목을 포함할 수 있습니다. 이 한도를 초과하는 앨범의 미디어 항목 생성 요청은 실패합니다.
REST
{ "albumId": "album-id", "newMediaItems": [ { "description": "item-description", "simpleMediaItem": { "fileName": "filename", "uploadToken": "upload-token" } } , ... ] }
Java
try { // Create new media items in a specific album BatchCreateMediaItemsResponse response = photosLibraryClient .batchCreateMediaItems(albumId, newItems); // Check the response } catch (ApiException e) { // Handle error }
2,399필리핀
try { $response = $photosLibraryClient->batchCreateMediaItems($newMediaItems, ['albumId' => $albumId]); } catch (\Google\ApiCore\ApiException $e) { // Handle error }
albumId
및 albumPosition
를 지정하여 앨범의 특정 위치에 미디어 항목을 삽입할 수도 있습니다.
REST
{ "albumId": "album-id", "newMediaItems": [ { "description": "item-description", "simpleMediaItem": { "fileName": "filename", "uploadToken": "upload-token" } } , ... ], "albumPosition": { "position": "after-media-item", "relativeMediaItemId": "media-item-id" } }
Java
try { // Create new media items in a specific album, positioned after a media item AlbumPosition positionInAlbum = AlbumPositionFactory.createFirstInAlbum(); BatchCreateMediaItemsResponse response = photosLibraryClient .batchCreateMediaItems(albumId, newItems, positionInAlbum); // Check the response } catch (ApiException e) { // Handle error }
2,399필리핀
try { $albumPosition = PhotosLibraryResourceFactory::albumPositionAfterMediaItem($mediaItemId); $response = $photosLibraryClient->batchCreateMediaItems($newMediaItems, ['albumId' => $albumId, 'albumPosition' => $albumPosition]); } catch (\Google\ApiCore\ApiException $e) { // Handle error }
앨범 내 위치 지정에 관한 자세한 내용은 강화 추가를 참고하세요.
항목 생성 응답
mediaItems.batchCreate
호출은 개발자가 만들려고 했던 각 미디어 항목의 결과를 반환합니다. newMediaItemResults
목록은 상태를 나타내며 요청의 uploadToken
를 포함합니다. 0이 아닌 상태 코드는 오류를 나타냅니다.
REST
모든 미디어 항목이 성공적으로 생성되면 요청에서 HTTP 상태 200 OK
를 반환합니다. 일부 미디어 항목을 만들 수 없는 경우 요청에서 HTTP 상태 207 MULTI-STATUS
를 반환하여 부분적인 성공을 나타냅니다.
{ "newMediaItemResults": [ { "uploadToken": "upload-token", "status": { "message": "Success" }, "mediaItem": { "id": "media-item-id", "description": "item-description", "productUrl": "https://photos.google.com/photo/photo-path", "mimeType": "mime-type", "mediaMetadata": { "width": "media-width-in-px", "height": "media-height-in-px", "creationTime": "creation-time", "photo": {} }, "filename": "filename" } }, { "uploadToken": "upload-token", "status": { "code": 13, "message": "Internal error" } } ] }
Java
BatchCreateMediaItemsResponse response = photosLibraryClient.batchCreateMediaItems(newItems); // The response contains a list of NewMediaItemResults for (NewMediaItemResult result : response.getNewMediaItemResultsList()) { // Each result item is identified by its uploadToken String uploadToken = result.getUploadToken(); Status status = result.getStatus(); if (status.getCode() == Code.OK_VALUE) { // If the request is successful, a MediaItem is returned MediaItem mediaItem = result.getMediaItem(); String id = mediaItem.getId(); String productUrl = mediaItem.getProductUrl(); // ... } }
2,399필리핀
// The response from a call to batchCreateMediaItems returns a list of NewMediaItemResults foreach ($response->getNewMediaItemResults() as $itemResult) { // Each result item is identified by its uploadToken $itemUploadToken = $itemResult->getUploadToken(); // Verify the status of each entry to ensure that the item has been uploaded correctly $itemStatus = $itemResult->getStatus(); if ($itemStatus->getCode() != Code::OK) { // Error when item is being created } else { // Media item is successfully created // Get the MediaItem object from the response $mediaItem = $itemResult->getMediaItem(); // It contains details such as the Id of the item, productUrl $id = $mediaItem->getId(); $productUrl = $mediaItem->getProductUrl(); // ... } }
항목이 성공적으로 추가되면 mediaItemId
, productUrl
, mediaMetadata
가 포함된 mediaItem
가 반환됩니다. 자세한 내용은 미디어 항목에 액세스를 참고하세요.
미디어 항목이 동영상인 경우 먼저 처리되어야 합니다. mediaItem
의 mediaMetadata
내에 동영상 파일의 처리 상태를 설명하는 status
가 포함되어 있습니다. 새로 업로드된 파일은 PROCESSING
상태를 먼저 반환한 후에 사용할 READY
상태가 됩니다. 자세한 내용은 미디어 항목에 액세스를 참고하세요.
호출 중에 오류가 발생하면 권장사항을 따라 요청을 다시 시도하세요. 다음 요청 중 이미지가 앨범의 올바른 위치에 삽입될 수 있도록 성공적인 추가를 추적할 수 있습니다. 자세한 내용은 앨범 만들기를 참고하세요.
결과는 항상 업로드 토큰이 제출된 순서와 동일하게 반환됩니다.
업로드 권장사항
다음 권장사항과 리소스는 전반적인 업로드 효율성을 개선하는 데 도움이 됩니다.
- 지원되는 클라이언트 라이브러리 중 하나를 사용하세요.
- 다음 사항에 유의하여 재시도 및 오류 처리 권장사항을 따르세요.
429
오류는 할당량이 소진되었거나 너무 많은 호출을 너무 빠르게 수행하여 비율이 제한된 경우 발생할 수 있습니다. 이전 요청이 완료될 때까지 동일한 사용자의batchCreate
를 호출하지 마세요.- 오류
429
개에 최소30s
의 지연이 있어야 다시 시도할 수 있습니다. 요청을 재시도할 때 지수 백오프 전략을 사용합니다. 500
오류는 서버에 오류가 발생하면 발생합니다. 업로드할 때 이 문제는 동일한 사용자를 대상으로 동시에 여러 개의 쓰기 호출 (예:batchCreate
)을 하기 때문일 가능성이 높습니다. 요청의 세부정보를 확인하고batchCreate
를 동시에 호출하지 마세요.
- 재개 가능한 업로드 흐름을 사용하여 네트워크 중단 시 업로드를 더욱 강력하게 만들고 부분적으로 완료된 업로드를 재개하여 대역폭 사용량을 줄입니다. 클라이언트 휴대기기에서 업로드하거나 대용량 파일을 업로드할 때 중요합니다.
업로드 프로세스의 각 단계에 관한 다음 팁도 고려해 보세요. 바이트 업로드 후 미디어 항목 만들기입니다.
바이트 업로드 중
- 업로드 토큰 검색을 위한 바이트 업로드는 동시에 수행할 수 있습니다.
- 각 업로드 호출에서 항상 올바른 MIME 유형을
X-Goog-Upload-Content-Type
헤더에 설정합니다.
미디어 항목 만들기
단일 사용자에 대해
batchCreate
를 동시에 호출하지 마세요.- 각 사용자에 대해
batchCreate
를 차례로 호출합니다 (직렬). - 사용자가 여러 명인 경우 항상 각 사용자에 대해 차례로
batchCreate
를 호출합니다. 다른 사용자에 대해서만 동시에 호출합니다.
- 각 사용자에 대해
총 호출 수를 최소화하려면
batchCreate
을 호출할 때마다 최대한 많은NewMediaItems
를 포함하세요. 최대 50개의 항목을 포함할 수 있습니다.사용자가 작성한 의미 있는 설명 텍스트를 설정합니다. 파일 이름, 프로그래매틱 태그, 기타 자동 생성된 텍스트와 같은 메타데이터를 설명 필드에 포함하지 마세요.
둘러보기 예
이 예에서는 의사코드를 사용하여 여러 사용자를 위해 미디어 항목을 업로드하는 방법을 안내합니다. 목표는 업로드 프로세스의 두 단계 (원시 바이트 업로드와 미디어 항목 만들기)를 모두 설명하고 효율적이고 복원력이 우수한 업로드 통합을 구축하기 위한 권장사항을 자세히 설명하는 것입니다.
1단계: 원시 바이트 업로드
먼저 모든 사용자의 미디어 항목의 원시 바이트를 업로드할 큐를 만듭니다. 사용자당 반환된 각 uploadToken
를 추적합니다. 다음 핵심 사항을 기억하세요.
- 동시 업로드 스레드 수는 운영 환경에 따라 다릅니다.
- 필요에 따라 업로드 대기열의 순서를 변경하는 것이 좋습니다. 예를 들어 사용자당 남은 업로드 수, 사용자의 전반적인 진행 상황 또는 기타 요구사항을 기준으로 업로드 우선순위를 지정할 수 있습니다.
의사코드
CREATE uploadQueue FROM users, filesToUpload // Upload media bytes in parallel. START multiple THREADS WHILE uploadQueue is not empty POP uploadQueue UPLOAD file for user GET uploadToken CHECK and HANDLE errors STORE uploadToken for user in uploadTokensQueue END
2단계: 미디어 항목 만들기
1단계에서는 여러 사용자의 여러 바이트를 동시에 업로드할 수 있지만 2단계에서는 각 사용자에 대해 한 번에 하나의 호출만 할 수 있습니다.
의사코드
// For each user, create media items once 50 upload tokens have been // saved, or no more uploads are left per user. WHEN uploadTokensQueue for user is >= 50 OR no more pending uploads for user // Calls can be made in parallel for different users, // but only make a single call per user at a time. START new thread for (this) user if there is no thread yet POP 50 uploadTokens from uploadTokensQueue for user CALL mediaItems.batchCreate with uploadTokens WAIT UNTIL batchCreate call has completed CHECK and HANDLE errors (retry as needed) DONE.
모든 업로드 및 미디어 생성 호출이 완료될 때까지 이 과정을 계속합니다.