تحميل بيانات الملف

تتيح لك Google Drive API تحميل بيانات الملف عند إنشاء File أو تعديله. لمزيد من المعلومات حول كيفية إنشاء ملف بيانات وصفية فقط، مثل مجلد، يمكنك الاطّلاع على إنشاء ملفات بيانات وصفية فقط.

يمكنك إجراء ثلاثة أنواع من عمليات التحميل:

  • التحميل البسيط (uploadType=media): استخدِم نوع التحميل هذا لنقل ملف وسائط صغير (5 ميغابايت أو أقل) بدون تقديم بيانات وصفية. لإجراء عملية تحميل بسيطة، يُرجى الرجوع إلى إجراء عملية تحميل بسيطة.

  • التحميل المتعدد الأجزاء (uploadType=multipart): "استخدِم نوع التحميل هذا لنقل ملف صغير (5 ميغابايت أو أقل) مع البيانات الوصفية التي تصف الملف، وذلك في طلب واحد. لتنفيذ عملية تحميل متعددة الأجزاء، يُرجى الرجوع إلى تنفيذ عملية تحميل متعددة الأجزاء.

  • التحميل القابل للاستئناف (uploadType=resumable): استخدِم نوع التحميل هذا للملفات الكبيرة (أكبر من 5 ميغابايت) وعندما يكون هناك احتمال كبير لحدوث انقطاع في الشبكة، مثلاً عند إنشاء ملف من تطبيق على الجهاز الجوّال. تُعد عمليات التحميل القابلة للاستئناف أيضًا خيارًا جيدًا لمعظم التطبيقات لأنّها تعمل أيضًا مع الملفات الصغيرة بتكلفة بسيطة تتمثّل في طلب HTTP إضافي واحد لكل عملية تحميل. لإجراء عملية تحميل قابلة للاستئناف، يُرجى الرجوع إلى إجراء عملية تحميل قابلة للاستئناف.

تنفّذ مكتبات عملاء Google API نوعًا واحدًا على الأقل من أنواع عمليات التحميل هذه. راجِع مستندات مكتبة العميل للحصول على تفاصيل إضافية حول كيفية استخدام كل نوع من الأنواع.

استخدام PATCH مقابل PUT

للتذكير، يتيح فعل HTTP PATCH تعديل جزء من مورد ملف، بينما يتيح فعل HTTP PUT استبدال المورد بالكامل. يُرجى العِلم أنّ PUT يمكن أن يؤدي إلى تغييرات غير متوافقة عند إضافة حقل جديد إلى مورد حالي.

عند تحميل ملف مصدر، اتّبِع الإرشادات التالية:

  • استخدِم فعل HTTP الموضّح في مرجع واجهة برمجة التطبيقات للطلب الأوّلي لعملية تحميل قابلة للاستئناف أو للطلب الوحيد لعملية تحميل بسيطة أو متعدّدة الأجزاء.
  • استخدِم PUT لجميع الطلبات اللاحقة لتحميل قابل للاستئناف بعد بدء الطلب. تؤدي هذه الطلبات إلى تحميل المحتوى بغض النظر عن الطريقة التي يتم استدعاؤها بها.

تنفيذ عملية تحميل بسيطة

لإجراء عملية تحميل بسيطة، استخدِم طريقة create في المورد files مع uploadType=media.

يوضّح ما يلي كيفية إجراء عملية تحميل بسيطة:

HTTP

  1. أنشئ طلب POST إلى عنوان URI الخاص بالطريقة /upload مع مَعلمة طلب البحث uploadType=media:

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media

  2. أضِف بيانات الملف إلى نص الطلب.

  3. أضِف عناوين HTTP التالية:

    • Content-Type. يجب ضبطها على نوع وسائط MIME الخاص بالكائن الذي يتم تحميله.
    • استبدِل Content-Length بعدد وحدات البايت التي تحمّلها. إذا كنت تستخدم ترميز النقل المجزّأ، لن يكون هذا العنوان مطلوبًا.
  4. أرسِل الطلب. في حال نجاح الطلب، يعرض الخادم رمز الحالة HTTP 200 OK مع البيانات الوصفية للملف. {HTTP}

JavaScript

/**
 * Uploads a file without metadata.
 *
 * @param {Blob|File} file The file to upload.
 * @param {string} accessToken A valid OAuth 2.0 access token.
 * @return {Promise<Object>} The uploaded file metadata.
 */
async function uploadFileSimple(file, accessToken) {
  const response = await fetch(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': file.type,
      },
      body: file,
    }
  );
  if (!response.ok) {
    throw new Error(`Upload failed: ${response.statusText}`);
  }
  return response.json();
}

عند إجراء عملية تحميل بسيطة، يتم إنشاء بيانات وصفية أساسية ويتم استنتاج بعض السمات من الملف، مثل نوع MIME أو modifiedTime. يمكنك استخدام عملية تحميل بسيطة في الحالات التي تتضمّن ملفات صغيرة ولا تكون فيها البيانات الوصفية للملفات مهمة.

إجراء عملية تحميل متعدّدة الأجزاء

يتيح لك طلب التحميل المتعدد الأجزاء تحميل البيانات الوصفية والبيانات في الطلب نفسه. استخدِم هذا الخيار إذا كانت البيانات التي ترسلها صغيرة بما يكفي لإعادة تحميلها بالكامل في حال تعذّر الاتصال.

لإجراء عملية تحميل متعدد الأجزاء، استخدِم الطريقة create في مورد files مع uploadType=multipart.

يوضّح ما يلي كيفية إجراء عملية تحميل متعدد الأجزاء:

جافا

drive/snippets/drive_v3/src/main/java/UploadBasic.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate use of Drive insert file API */
public class UploadBasic {

  /**
   * Upload new file.
   *
   * @return Inserted file metadata if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static String uploadBasic() throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();
    // Upload file photo.jpg on drive.
    File fileMetadata = new File();
    fileMetadata.setName("photo.jpg");
    // File's content.
    java.io.File filePath = new java.io.File("files/photo.jpg");
    // Specify media type and file-path for file.
    FileContent mediaContent = new FileContent("image/jpeg", filePath);
    try {
      File file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to upload file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/upload_basic.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
  """Insert new file.
  Returns : Id's of the file uploaded

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create drive api client
    service = build("drive", "v3", credentials=creds)

    file_metadata = {"name": "download.jpeg"}
    media = MediaFileUpload("download.jpeg", mimetype="image/jpeg")
    # pylint: disable=maybe-no-member
    file = (
        service.files()
        .create(body=file_metadata, media_body=media, fields="id")
        .execute()
    )
    print(f'File ID: {file.get("id")}')

  except HttpError as error:
    print(f"An error occurred: {error}")
    file = None

  return file.get("id")


if __name__ == "__main__":
  upload_basic()

Node.js

drive/snippets/drive_v3/file_snippets/upload_basic.js
import fs from 'node:fs';
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Uploads a file to Google Drive.
 * @return {Promise<string|null|undefined>} The ID of the uploaded file.
 */
async function uploadBasic() {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // The request body for the file to be uploaded.
  const requestBody = {
    name: 'photo.jpg',
    fields: 'id',
  };

  // The media content to be uploaded.
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };

  // Upload the file.
  const file = await service.files.create({
    requestBody,
    media,
  });

  // Print the ID of the uploaded file.
  console.log('File Id:', file.data.id);
  return file.data.id;
}

JavaScript

/**
 * Uploads a file along with its metadata.
 *
 * @param {Blob|File} file The file to upload.
 * @param {string} accessToken A valid OAuth 2.0 access token.
 * @return {Promise<Object>} The uploaded file metadata.
 */
async function uploadFileMultipart(file, accessToken) {
  const metadata = {
    name: file.name,
  };

  const boundary = 'foo_bar_baz';
  const delimiter = `\r\n--${boundary}\r\n`;
  const closeDelimiter = `\r\n--${boundary}--`;

  const requestBody = new Blob([
    `--${boundary}\r\n`,
    'Content-Type: application/json; charset=UTF-8\r\n\r\n',
    JSON.stringify(metadata),
    delimiter,
    `Content-Type: ${file.type}\r\n\r\n`,
    file,
    closeDelimiter,
  ]);

  const response = await fetch(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': `multipart/related; boundary=${boundary}`,
      },
      body: requestBody,
    }
  );
  if (!response.ok) {
    throw new Error(`Upload failed: ${response.statusText}`);
  }
  return response.json();
}

PHP

drive/snippets/drive_v3/src/DriveUploadBasic.php
<?php
use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
        'name' => 'photo.jpg'));
        $content = file_get_contents('../files/photo.jpg');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => 'image/jpeg',
            'uploadType' => 'multipart',
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    } 

}

NET.

drive/snippets/drive_v3/DriveV3Snippets/UploadBasic.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use of Drive insert file API
    public class UploadBasic
    {
        /// <summary>
        /// Upload new file.
        /// </summary>
        /// <param name="filePath">Image path to upload.</param>
        /// <returns>Inserted file metadata if successful, null otherwise.</returns>
        public static string DriveUploadBasic(string filePath)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Upload file photo.jpg on drive.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "photo.jpg"
                };
                FilesResource.CreateMediaUpload request;
                // Create a new file on drive.
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    // Create a new file, with metadata and stream.
                    request = service.Files.Create(
                        fileMetadata, stream, "image/jpeg");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the uploaded file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine("File not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

HTTP

  1. أنشئ طلب POST إلى عنوان URI الخاص بالطريقة /upload مع مَعلمة طلب البحث uploadType=multipart:

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart

  1. أنشئ نص الطلب. يجب تنسيق نص الطلب وفقًا لنوع المحتوى المتعدد الأجزاء/المرتبط MIME المدرَج ضمن RFC 2387، والذي يتضمّن جزأين:

    • البيانات الوصفية. يجب أن تأتي البيانات الوصفية أولاً وأن تتضمّن Content-Type عنوانًا مضبوطًا على application/json; charset=UTF-8. أضِف البيانات الوصفية للملف بتنسيق JSON.
    • الوسائط يجب أن تأتي الوسائط في المرتبة الثانية وأن تتضمّن عنوان Content-Type بأي نوع MIME. أضِف بيانات الملف إلى جزء الوسائط. حدِّد كل جزء باستخدام سلسلة حدودية، مسبوقة بشرطتين. بالإضافة إلى ذلك، أضِف شرطتَين بعد سلسلة الحدود النهائية.
    1. أضِف عناوين HTTP التالية ذات المستوى الأعلى:

      • Content-Type. اضبط القيمة على multipart/related وأدرِج سلسلة الحدود التي تستخدمها لتحديد الأجزاء المختلفة من الطلب. على سبيل المثال: Content-Type: multipart/related; boundary=foo_bar_baz
      • Content-Length: اضبطها على إجمالي عدد وحدات البايت في نص الطلب.
    2. أرسِل الطلب.

    لإنشاء جزء البيانات الوصفية أو تعديله فقط، بدون البيانات المرتبطة به، أرسِل طلب POST أو PATCH إلى نقطة نهاية المورد العادية: https://www.googleapis.com/drive/v3/files في حال نجاح الطلب، سيعرض الخادم رمز الحالة HTTP 200 OK مع البيانات الوصفية للملف.

عند إنشاء الملفات، يجب تحديد إضافة اسم الملف في الحقل name الخاص بالملف. على سبيل المثال، عند إنشاء ملف JPEG لصورة، يمكنك تحديد شيء مثل "name": "photo.jpg" في البيانات الوصفية. تعرض طلبات لاحقة إلى الطريقة get السمة fileExtension للقراءة فقط التي تحتوي على الامتداد المحدّد أصلاً في الحقل name.

إجراء عملية تحميل قابلة للاستئناف

تتيح لك عملية التحميل القابلة للاستئناف استئناف عملية تحميل بعد أن يؤدي عطل في الاتصال إلى مقاطعة تدفّق البيانات. وبما أنّك لست مضطرًا إلى إعادة بدء عمليات تحميل الملفات الكبيرة، يمكن أن تقلّل عمليات التحميل القابلة للاستئناف أيضًا من استخدامك لمعدل نقل البيانات في حال حدوث عطل في الشبكة.

تكون عمليات التحميل القابلة للاستئناف مفيدة عندما تختلف أحجام الملفات بشكل كبير أو عندما يكون هناك حد زمني ثابت للطلبات (مثل مهام الخلفية في نظام التشغيل على الأجهزة الجوّالة وبعض طلبات App Engine). يمكنك أيضًا استخدام عمليات التحميل القابلة للاستئناف في الحالات التي تريد فيها عرض شريط تقدّم عملية التحميل.

تتألف عملية التحميل القابلة للاستئناف من عدة خطوات عالية المستوى:

  1. أرسِل الطلب الأوّلي واسترجِع معرّف الموارد المنتظم الخاص بالجلسة القابلة للاستئناف.
  2. حمِّل البيانات وراقِب حالة التحميل.
  3. (اختياري) إذا تعذّر إكمال عملية التحميل، استأنِفها.

إرسال الطلب الأوّلي

لبدء عملية تحميل قابلة للاستئناف، استخدِم الطريقة create في المورد files مع uploadType=resumable.

HTTP

  1. أنشئ طلب POST إلى عنوان URI الخاص بالطريقة /upload مع مَعلمة طلب البحث uploadType=resumable:

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable

    إذا نجح طلب بدء عملية الربط، ستتضمّن الاستجابة رمز حالة HTTP‏ 200 OK. بالإضافة إلى ذلك، يتضمّن الردّ عنوان Location يحدّد معرّف الموارد المنتظم (URI) للجلسة القابلة للاستئناف:

    HTTP/1.1 200 OK
    Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
    Content-Length: 0
    

    احفظ معرّف الموارد المنتظم (URI) الخاص بالجلسة القابلة للاستئناف حتى تتمكّن من تحميل بيانات الملف والاستعلام عن حالة التحميل. تنتهي صلاحية معرّف الموارد المنتظم (URI) الخاص بالجلسة القابلة للاستئناف بعد أسبوع واحد.

    لتعديل ملف حالي، استخدِم PATCH.

  2. إذا كانت لديك بيانات وصفية للملف، أضِفها إلى نص الطلب بتنسيق JSON. بخلاف ذلك، اترُك نص الطلب فارغًا.

  3. أضِف عناوين HTTP التالية:

    • X-Upload-Content-Type: اختيارية. يجب ضبطه على نوع MIME لبيانات الملف، والتي يتم نقلها في الطلبات اللاحقة. إذا لم يتم تحديد نوع MIME للبيانات في البيانات الوصفية أو من خلال هذا العنوان، سيتم عرض العنصر بالتنسيق application/octet-stream.
    • X-Upload-Content-Length: اختيارية. يجب ضبطها على عدد وحدات البايت لبيانات الملف، والتي يتم نقلها في الطلبات اللاحقة.
    • Content-Type: مطلوب إذا كانت لديك بيانات وصفية للملف. اضبط القيمة على application/json; charset=UTF-8.
    • Content-Length: مطلوبة ما لم تستخدم ترميز النقل المقسَّم. يجب ضبطها على عدد وحدات البايت في نص هذا الطلب الأوّلي.
  4. أرسِل الطلب. في حال نجاح طلب بدء الجلسة، ستتضمّن الاستجابة رمز الحالة 200 OK HTTP مع نص فارغ. بالإضافة إلى ذلك، تتضمّن الاستجابة عنوان Location يحدّد معرّف الموارد المنتظم (URI) للجلسة القابلة للاستئناف. استخدِم معرّف الموارد الموحّد الخاص بالجلسة القابلة للاستئناف لتحميل بيانات الملف والاستعلام عن حالة التحميل. تنتهي صلاحية معرّف الموارد المنتظم لجلسة قابلة للاستئناف بعد أسبوع واحد.

  5. انسخ عنوان URL للجلسة القابلة للاستئناف واحفظه.

  6. انتقِل إلى تحميل المحتوى.

JavaScript

/**
 * Initiates a resumable upload session and returns the session URI.
 *
 * @param {Blob|File} file The file to upload.
 * @param {string} accessToken A valid OAuth 2.0 access token.
 * @return {Promise<string>} The resumable session URI.
 */
async function initiateResumableUpload(file, accessToken) {
  const metadata = {
    name: file.name,
    mimeType: file.type,
  };

  const response = await fetch(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json; charset=UTF-8',
        'X-Upload-Content-Type': file.type,
        'X-Upload-Content-Length': file.size,
      },
      body: JSON.stringify(metadata),
    }
  );
  if (!response.ok) {
    throw new Error(`Failed to initiate upload: ${response.statusText}`);
  }
  return response.headers.get('Location');
}

تحميل المحتوى

تتوفّر طريقتان لتحميل ملف باستخدام جلسة قابلة للاستئناف:

  • تحميل المحتوى في طلب واحد: استخدِم هذا الأسلوب عندما يمكن تحميل الملف في طلب واحد، أو إذا لم يكن هناك حد زمني ثابت لأي طلب واحد، أو إذا لم تكن بحاجة إلى عرض مؤشر لتقدّم عملية التحميل. هذه الطريقة هي الأفضل لأنّها تتطلّب عددًا أقل من الطلبات وتؤدي إلى تحسين الأداء.
  • تحميل المحتوى في أجزاء متعددة: استخدِم هذه الطريقة إذا كان عليك تقليل مقدار البيانات التي يتم نقلها في أي طلب واحد. قد تحتاج إلى تقليل البيانات المنقولة عندما يكون هناك حد زمني ثابت لكل طلب على حدة، كما هو الحال بالنسبة إلى فئات معيّنة من طلبات App Engine. ويكون هذا النهج مفيدًا أيضًا إذا كان عليك تقديم مؤشر مخصّص لعرض مستوى تقدّم عملية التحميل.

‫HTTP - طلب واحد

  1. أنشئ طلب PUT لمعرّف الموارد المنتظم (URI) الخاص بالجلسة القابلة للاستئناف.
  2. أضِف بيانات الملف إلى نص الطلب.
  3. أضِف عنوان HTTP باسم Content-Length، واضبطه على عدد البايت في الملف.
  4. أرسِل الطلب. في حال انقطاع طلب التحميل أو تلقّي الرد 5xx، اتّبِع الإجراءات الواردة في استئناف عملية تحميل متوقّفة.

JavaScript - طلب واحد

/**
 * Uploads the entire file in a single request using the session URI.
 *
 * @param {string} sessionUrl The resumable session URI.
 * @param {Blob|File} file The file to upload.
 * @return {Promise<Object>} The uploaded file metadata.
 */
async function uploadFileSingleRequest(sessionUrl, file) {
  const response = await fetch(sessionUrl, {
    method: 'PUT',
    headers: {
      'Content-Length': file.size,
    },
    body: file,
  });
  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
  }
  return response.json();
}

HTTP - طلبات متعدّدة

  1. أنشئ طلب PUT لمعرّف الموارد المنتظم (URI) الخاص بالجلسة القابلة للاستئناف.

  2. أضِف بيانات الجزء إلى نص الطلب. أنشئ أجزاءً بحجم مضاعفات 256 كيلوبايت (256 × 1024 بايت)، باستثناء الجزء الأخير الذي يكمل عملية التحميل. يجب أن يكون حجم الأجزاء كبيرًا قدر الإمكان لضمان فعالية عملية التحميل.

  3. أضِف عناوين HTTP التالية:

    • Content-Length. يتم ضبطها على عدد وحدات البايت في الجزء الحالي.
    • Content-Range: اضبط هذا الخيار لعرض وحدات البايت في الملف الذي تحمّله. على سبيل المثال، يشير Content-Range: bytes 0-524287/2000000 إلى أنّك تحمّل أول 524,288 بايت (256 × 1024 × 2) في ملف يبلغ حجمه 2,000,000 بايت.
  4. أرسِل الطلب وعالِج الردّ. في حال انقطاع عملية التحميل أو تلقّي الرد 5xx، اتّبِع الإجراءات الواردة في استئناف عملية تحميل متوقّفة.

  5. كرِّر الخطوات من 1 إلى 4 لكل جزء متبقٍّ في الملف. استخدِم العنوان Range في الاستجابة لتحديد مكان بدء الجزء التالي. لا تفترض أنّ الخادم تلقّى جميع وحدات البايت المُرسَلة في الطلب السابق.

عند اكتمال عملية تحميل الملف بأكملها، ستتلقّى الرد 200 OK أو 201 Created، بالإضافة إلى أي بيانات وصفية مرتبطة بالمرجع.

JavaScript - طلبات متعدّدة

/**
 * Uploads a file in chunks of a specified size.
 *
 * @param {string} sessionUrl The resumable session URI.
 * @param {Blob|File} file The file to upload.
 * @param {number} chunkSize Chunk size in bytes (must be a multiple of 256 KB).
 * @return {Promise<Object>} The uploaded file metadata.
 */
async function uploadFileChunked(sessionUrl, file, chunkSize = 1024 * 1024) {
  let start = 0;
  while (start < file.size) {
    const end = Math.min(start + chunkSize, file.size);
    const chunk = file.slice(start, end);
    const chunkLength = end - start;

    const response = await fetch(sessionUrl, {
      method: 'PUT',
      headers: {
        'Content-Length': chunkLength,
        'Content-Range': `bytes ${start}-${end - 1}/${file.size}`,
      },
      body: chunk,
    });

    if (response.status === 308) {
      // 308 Resume Incomplete indicates chunk was received successfully.
      start = end;
    } else if (response.ok) {
      // 200 OK or 201 Created indicates the upload is fully complete.
      return response.json();
    } else {
      throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
    }
  }
}

استئناف عملية تحميل تمت مقاطعتها

إذا تم إنهاء طلب تحميل قبل تلقّي ردّ، أو إذا تلقّيت الردّ 503 Service Unavailable، عليك استئناف عملية التحميل التي تمّت مقاطعتها.

HTTP

  1. لطلب حالة التحميل، أنشئ طلب PUT فارغًا إلى معرّف الموارد المنتظم الخاص بالجلسة القابلة للاستئناف.

  2. أضِف العنوان Content-Range للإشارة إلى أنّ الموضع الحالي في الملف غير معروف. على سبيل المثال، اضبط قيمة Content-Range على */2000000 إذا كان إجمالي طول الملف 2,000,000 بايت. إذا كنت لا تعرف الحجم الكامل للملف، اضبط قيمة Content-Range على */*.

  3. أرسِل الطلب.

  4. معالجة الردّ:

    • يشير الردّ 200 OK أو 201 Created إلى أنّ عملية التحميل قد اكتملت، ولا يلزم اتّخاذ أي إجراء آخر.
    • تشير الاستجابة 308 Resume Incomplete إلى أنّه عليك مواصلة تحميل الملف.
    • تشير الاستجابة 404 Not Found إلى أنّ جلسة التحميل انتهت صلاحيتها ويجب إعادة بدء عملية التحميل من البداية.
  5. إذا تلقّيت استجابة 308 Resume Incomplete، عالِج عنوان Range في الاستجابة لتحديد عدد البايتات التي تلقّاها الخادم. إذا لم يتضمّن الردّ عنوان Range، هذا يعني أنّه لم يتم تلقّي أي وحدات بايت. على سبيل المثال، يشير العنوان Range الذي يتضمّن bytes=0-42 إلى أنّه تم تلقّي أول 43 بايت من الملف، وأنّ الجزء التالي الذي سيتم تحميله سيبدأ بالبايت رقم 44.

  6. بعد أن عرفت المكان الذي يمكنك استئناف التحميل منه، واصِل تحميل الملف بدءًا من البايت التالي. أدرِج عنوان Content-Range لتحديد الجزء الذي ترسله من الملف. على سبيل المثال، يشير Content-Range: bytes 43-1999999 إلى أنّك سترسل البايتات من 44 إلى 2,000,000.

JavaScript

/**
 * Resumes an interrupted upload by querying the status and uploading remaining bytes.
 *
 * @param {string} sessionUrl The resumable session URI.
 * @param {Blob|File} file The file being uploaded.
 * @return {Promise<Object>} The uploaded file metadata.
 */
async function resumeUpload(sessionUrl, file) {
  // 1. Query the upload status by sending an empty PUT request
  const statusResponse = await fetch(sessionUrl, {
    method: 'PUT',
    headers: {
      'Content-Range': `bytes */${file.size}`,
    },
  });

  if (statusResponse.ok) {
    // Already completed
    return statusResponse.json();
  }

  if (statusResponse.status !== 308) {
    throw new Error(`Failed to query upload status: ${statusResponse.statusText}`);
  }

  // 2. Parse the Range header to determine received bytes
  const rangeHeader = statusResponse.headers.get('Range');
  let startOffset = 0;
  if (rangeHeader) {
    const parts = rangeHeader.split('-');
    startOffset = parseInt(parts[1], 10) + 1;
  }

  // 3. Upload the remaining content of the file
  const remainingChunk = file.slice(startOffset);
  const response = await fetch(sessionUrl, {
    method: 'PUT',
    headers: {
      'Content-Length': remainingChunk.size,
      'Content-Range': `bytes ${startOffset}-${file.size - 1}/${file.size}`,
    },
    body: remainingChunk,
  });

  if (!response.ok) {
    throw new Error(`Resume upload failed: ${response.statusText}`);
  }
  return response.json();
}

التعامل مع أخطاء تحميل الوسائط

عند تحميل وسائط، اتّبِع أفضل الممارسات التالية للتعامل مع الأخطاء:

  • بالنسبة إلى أخطاء 5xx، استأنِف عمليات التحميل أو أعِد محاولة تنفيذها إذا تعذّرت بسبب انقطاع الاتصال. لمزيد من المعلومات حول التعامل مع أخطاء 5xx، يُرجى الاطّلاع على مقالة الأخطاء 500 و502 و503 و504.
  • بالنسبة إلى أخطاء 403 rate limit، أعِد محاولة التحميل. لمزيد من المعلومات حول التعامل مع أخطاء 403 rate limit، يُرجى الرجوع إلى الخطأ 403: rateLimitExceeded.
  • بالنسبة إلى أي أخطاء 4xx (بما في ذلك 403) تحدث أثناء عملية تحميل قابلة للاستئناف، عليك إعادة تشغيل عملية التحميل. تشير هذه الأخطاء إلى أنّ مهلة جلسة التحميل قد انتهت ويجب إعادة تشغيلها من خلال طلب معرّف موارد منتظم جديد للجلسة. تنتهي أيضًا صلاحية جلسات التحميل بعد أسبوع واحد من عدم النشاط.

أنواع الاستيراد إلى "مستندات Google"

عند إنشاء ملف في Drive، قد تحتاج إلى تحويله إلى نوع ملف Google Workspace، مثل &quot;مستندات Google&quot; أو &quot;جداول بيانات Google&quot;. على سبيل المثال، قد تريد تحويل مستند من معالج الكلمات المفضّل لديك إلى &quot;مستندات Google&quot; للاستفادة من ميزاته.

لتحويل ملف إلى نوع ملف معيّن من Google Workspace، حدِّد Google Workspace mimeType عند إنشاء الملف.

في ما يلي كيفية تحويل ملف CSV إلى جدول بيانات Google Workspace:

جافا

drive/snippets/drive_v3/src/main/java/UploadWithConversion.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate Drive's upload with conversion use-case. */
public class UploadWithConversion {

  /**
   * Upload file with conversion.
   *
   * @return Inserted file id if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static String uploadWithConversion() throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    // File's metadata.
    File fileMetadata = new File();
    fileMetadata.setName("My Report");
    fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");

    java.io.File filePath = new java.io.File("files/report.csv");
    FileContent mediaContent = new FileContent("text/csv", filePath);
    try {
      File file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to move file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/upload_with_conversion.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_with_conversion():
  """Upload file with conversion
  Returns: ID of the file uploaded

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create drive api client
    service = build("drive", "v3", credentials=creds)

    file_metadata = {
        "name": "My Report",
        "mimeType": "application/vnd.google-apps.spreadsheet",
    }
    media = MediaFileUpload("report.csv", mimetype="text/csv", resumable=True)
    # pylint: disable=maybe-no-member
    file = (
        service.files()
        .create(body=file_metadata, media_body=media, fields="id")
        .execute()
    )
    print(f'File with ID: "{file.get("id")}" has been uploaded.')

  except HttpError as error:
    print(f"An error occurred: {error}")
    file = None

  return file.get("id")


if __name__ == "__main__":
  upload_with_conversion()

Node.js

drive/snippets/drive_v3/file_snippets/upload_with_conversion.js
import fs from 'node:fs';
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Uploads a file to Google Drive and converts it to a Google Sheet.
 * @return {Promise<string|null|undefined>} The ID of the uploaded file.
 */
async function uploadWithConversion() {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // The metadata for the file to be uploaded and converted.
  const fileMetadata = {
    name: 'My Report',
    // The MIME type to convert the file to.
    mimeType: 'application/vnd.google-apps.spreadsheet',
  };

  // The media content to be uploaded.
  const media = {
    mimeType: 'text/csv',
    body: fs.createReadStream('files/report.csv'),
  };

  // Upload the file with conversion.
  const file = await service.files.create({
    requestBody: fileMetadata,
    media,
    fields: 'id',
  });

  // Print the ID of the uploaded file.
  console.log('File Id:', file.data.id);
  return file.data.id;
}

PHP

drive/snippets/drive_v3/src/DriveUploadWithConversion.php
<?php
use Google\Client;
use Google\Service\Drive;
function uploadWithConversion()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
            'name' => 'My Report',
            'mimeType' => 'application/vnd.google-apps.spreadsheet'));
        $content = file_get_contents('../files/report.csv');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => 'text/csv',
            'uploadType' => 'multipart',
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    }

}

NET.

drive/snippets/drive_v3/DriveV3Snippets/UploadWithConversion.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate Drive's upload with conversion use-case.
    public class UploadWithConversion
    {
        /// <summary>
        /// Upload file with conversion.
        /// </summary>
        /// <param name="filePath">Id of the spreadsheet file.</param>
        /// <returns>Inserted file id if successful, null otherwise.</returns>
        public static string DriveUploadWithConversion(string filePath)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Upload file My Report on drive.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "My Report",
                    MimeType = "application/vnd.google-apps.spreadsheet"
                };
                FilesResource.CreateMediaUpload request;
                // Create a new drive.
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    // Create a new file, with metadata and stream.
                    request = service.Files.Create(
                        fileMetadata, stream, "text/csv");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the uploaded file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine("File not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

لمعرفة ما إذا كان التحويل متاحًا، تحقَّق من حقل importFormats في المرجع about قبل إنشاء الملف. تتوفّر الإحالات الناجحة المتوافقة بشكل ديناميكي في هذه المصفوفة. في ما يلي بعض تنسيقات الاستيراد الشائعة:

منإلى
Microsoft Word وOpenDocument Text وHTML وRTF والنص العادي وMarkdownمستندات Google
Microsoft Excel وOpenDocument Spreadsheet وCSV وTSV والنص العاديجداول بيانات Google
Microsoft PowerPoint، عرض تقديمي من OpenDocumentالعروض التقديمية من Google
‫JPEG أو PNG أو GIF أو BMP أو PDF"مستندات Google" (تضمين الصورة في مستند)
نص عادي (نوع MIME خاص)، JSONلغة برمجة تطبيقات Google

عند تحميل الوسائط وتحويلها أثناء update طلب إلى ملف "مستندات Google" أو "جداول بيانات Google" أو "العروض التقديمية من Google"، يتم استبدال المحتوى الكامل للمستند.

عند تحويل صورة إلى مستند Google، يستخدم Drive تكنولوجيا التعرّف البصري على الأحرف (OCR) لتحويل الصورة إلى نص. يمكنك تحسين جودة خوارزمية التعرّف البصري على الحروف من خلال تحديد رمز اللغة BCP 47 المناسب في المَعلمة ocrLanguage. يظهر النص المستخرَج في المستند بجانب الصورة المضمّنة.

استخدام معرّف تم إنشاؤه مسبقًا لتحميل الملفات

تتيح لك Drive API استرداد قائمة بمعرّفات الملفات التي تم إنشاؤها مسبقًا والتي يمكن استخدامها لإنشاء الموارد ونسخها وتحميلها. لمزيد من المعلومات، يُرجى الاطّلاع على إنشاء أرقام تعريف لاستخدامها مع ملفاتك.

يمكنك إعادة محاولة عمليات التحميل بأمان باستخدام المعرّفات التي تم إنشاؤها مسبقًا في حال حدوث خطأ غير محدّد في الخادم أو انتهاء المهلة. في حال نجاح إجراء الملف، ستعرض عمليات إعادة المحاولة اللاحقة رمز الاستجابة 409 Conflict لحالة HTTP، ولن يتم إنشاء ملفات مكررة.

يُرجى العِلم أنّه لا يمكن استخدام المعرّفات التي تم إنشاؤها مسبقًا لإنشاء ملفات Google Workspace، باستثناء application/vnd.google-apps.drive-sdk وapplication/vnd.google-apps.folder أنواع MIME. وبالمثل، لا تتوفّر عمليات التحميل التي تشير إلى تحويل إلى تنسيق ملف Google Workspace.

تحديد النص القابل للفهرسة لأنواع الملفات غير المعروفة

يمكن للمستخدمين استخدام واجهة مستخدم Drive للعثور على محتوى المستند. يمكنك أيضًا استخدام طريقة list في المرجع files والحقل fullText للبحث عن محتوى من تطبيقك. لمزيد من المعلومات، راجِع البحث عن الملفات والمجلدات.

يفهرس Drive المستندات تلقائيًا للبحث عندما يتعرّف على نوع الملف، بما في ذلك المستندات النصية وملفات PDF والصور التي تحتوي على نص وأنواع أخرى شائعة. إذا كان تطبيقك يحفظ أنواعًا أخرى من الملفات (مثل الرسومات والفيديوهات والاختصارات)، يمكنك تحسين إمكانية العثور عليها من خلال توفير نص قابل للفهرسة في الحقل contentHints.indexableText الخاص بالملف.

لمزيد من المعلومات حول النص القابل للفهرسة، يُرجى الاطّلاع على إدارة البيانات الوصفية للملفات.