Using files

L'API Gemini supporta il caricamento dei file multimediali separatamente dall'input del prompt, consentendo di riutilizzarli in più richieste e più prompt. Per maggiori dettagli, consulta la guida Richieste con contenuti multimediali.

Metodo: media.upload

Crea un File.

Endpoint

  • URI di caricamento, per le richieste di caricamento di contenuti multimediali:
pubblica https://generativelanguage.googleapis.com/upload/v1beta/files
  • URI metadati, per richieste solo di metadati:
post https://generativelanguage.googleapis.com/v1beta/files

Corpo della richiesta

Il corpo della richiesta contiene dati con la seguente struttura:

Campi
file object (File)

(Facoltativo) Metadati del file da creare.

Esempio di richiesta

Immagine

Python

import google.generativeai as genai

myfile = genai.upload_file(media / "Cajun_instruments.jpg")
print(f"{myfile=}")

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content(
    [myfile, "\n\n", "Can you tell me about the instruments in this photo?"]
)
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/jetpack.jpg`,
  {
    mimeType: "image/jpeg",
    displayName: "Jetpack drawing",
  },
);
// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Tell me about this image.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

Vai

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "Cajun_instruments.jpg"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx,
	genai.FileData{URI: file.URI},
	genai.Text("Can you tell me about the instruments in this photo?"))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

Conchiglia

MIME_TYPE=$(file -b --mime-type "${IMG_PATH_2}")
NUM_BYTES=$(wc -c < "${IMG_PATH_2}")
DISPLAY_NAME=TEXT

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${IMG_PATH_2}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you tell me about the instruments in this photo?"},
          {"file_data":
            {"mime_type": "image/jpeg", 
            "file_uri": '$file_uri'}
        }]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Audio

Python

import google.generativeai as genai

myfile = genai.upload_file(media / "sample.mp3")
print(f"{myfile=}")

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content([myfile, "Describe this audio clip"])
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/samplesmall.mp3`,
  {
    mimeType: "audio/mp3",
    displayName: "Audio sample",
  },
);

let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
  process.stdout.write(".");
  // Sleep for 10 seconds
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  // Fetch the file from the API again
  file = await fileManager.getFile(uploadResult.file.name);
}

if (file.state === FileState.FAILED) {
  throw new Error("Audio processing failed.");
}

// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Tell me about this audio clip.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

Vai

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "sample.mp3"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx,
	genai.FileData{URI: file.URI},
	genai.Text("Describe this audio clip"))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

Conchiglia

MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${AUDIO_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Describe this audio clip"},
          {"file_data":{"mime_type": "audio/mp3", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Testo

Python

import google.generativeai as genai

myfile = genai.upload_file(media / "poem.txt")
print(f"{myfile=}")

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content(
    [myfile, "\n\n", "Can you add a few more lines to this poem?"]
)
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
  displayName: "Apollo 11",
});
// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Transcribe the first few sentences of this document.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

Vai

// Set MIME type explicitly for text files - the service may have difficulty
// distingushing between different MIME types of text files automatically.
file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "poem.txt"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx,
	genai.FileData{URI: file.URI},
	genai.Text("Can you add a few more lines to this poem?"))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

Conchiglia

MIME_TYPE=$(file -b --mime-type "${TEXT_PATH}")
NUM_BYTES=$(wc -c < "${TEXT_PATH}")
DISPLAY_NAME=TEXT

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${TEXT_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you add a few more lines to this poem?"},
          {"file_data":{"mime_type": "text/plain", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

name=$(jq ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
# Print some information about the file you got
name=$(jq ".file.name" file_info.json)
echo name=$name
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name?key=$GOOGLE_API_KEY

Video

Python

import google.generativeai as genai

import time

# Video clip (CC BY 3.0) from https://peach.blender.org/download/
myfile = genai.upload_file(media / "Big_Buck_Bunny.mp4")
print(f"{myfile=}")

# Videos need to be processed before you can use them.
while myfile.state.name == "PROCESSING":
    print("processing video...")
    time.sleep(5)
    myfile = genai.get_file(myfile.name)

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content([myfile, "Describe this video clip"])
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/Big_Buck_Bunny.mp4`,
  {
    mimeType: "video/mp4",
    displayName: "Big Buck Bunny",
  },
);

let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
  process.stdout.write(".");
  // Sleep for 10 seconds
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  // Fetch the file from the API again
  file = await fileManager.getFile(uploadResult.file.name);
}

if (file.state === FileState.FAILED) {
  throw new Error("Video processing failed.");
}

// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Tell me about this video.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

Vai

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "earth.mp4"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

// Videos need to be processed before you can use them.
for file.State == genai.FileStateProcessing {
	log.Printf("processing %s", file.Name)
	time.Sleep(5 * time.Second)
	var err error
	if file, err = client.GetFile(ctx, file.Name); err != nil {
		log.Fatal(err)
	}
}
if file.State != genai.FileStateActive {
	log.Fatalf("uploaded file has state %s, not active", file.State)
}

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx,
	genai.FileData{URI: file.URI},
	genai.Text("Describe this video clip"))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

Conchiglia

MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO_PATH

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${VIDEO_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

state=$(jq ".file.state" file_info.json)
echo state=$state

# Ensure the state of the video is 'ACTIVE'
while [[ "($state)" = *"PROCESSING"* ]];
do
  echo "Processing video..."
  sleep 5
  # Get the file of interest to check state
  curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
  state=$(jq ".file.state" file_info.json)
done

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Describe this video clip"},
          {"file_data":{"mime_type": "video/mp4", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

PDF

Python

import google.generativeai as genai

model = genai.GenerativeModel("gemini-1.5-flash")
sample_pdf = genai.upload_file(media / "test.pdf")
response = model.generate_content(["Give me a summary of this pdf file.", sample_pdf])
print(response.text)

Corpo della risposta

Risposta per media.upload.

In caso di esito positivo, il corpo della risposta contiene dati con la seguente struttura:

Campi
file object (File)

Metadati del file creato.

Rappresentazione JSON
{
  "file": {
    object (File)
  }
}

Metodo: files.get

Recupera i metadati per il File specificato.

Endpoint

get https://generativelanguage.googleapis.com/v1beta/{name=files/*}

Parametri del percorso

name string

Obbligatorio. Il nome di File da recuperare. Esempio: files/abc-123 assume la forma files/{file}.

Corpo della richiesta

Il corpo della richiesta deve essere vuoto.

Esempio di richiesta

Python

import google.generativeai as genai

myfile = genai.upload_file(media / "poem.txt")
file_name = myfile.name
print(file_name)  # "files/*"

myfile = genai.get_file(file_name)
print(myfile)

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResponse = await fileManager.uploadFile(
  `${mediaPath}/jetpack.jpg`,
  {
    mimeType: "image/jpeg",
    displayName: "Jetpack drawing",
  },
);

// Get the previously uploaded file's metadata.
const getResponse = await fileManager.getFile(uploadResponse.file.name);

// View the response.
console.log(
  `Retrieved file ${getResponse.displayName} as ${getResponse.uri}`,
);

Vai

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "personWorkingOnComputer.jpg"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

gotFile, err := client.GetFile(ctx, file.Name)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Got file:", gotFile.Name)

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx,
	genai.FileData{URI: file.URI},
	genai.Text("Describe this image"))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

Conchiglia

name=$(jq ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
# Print some information about the file you got
name=$(jq ".file.name" file_info.json)
echo name=$name
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

Corpo della risposta

In caso di esito positivo, il corpo della risposta contiene un'istanza di File.

Metodo: files.list

Elenca i metadati per i file File di proprietà del progetto richiedente.

Endpoint

recupera https://generativelanguage.googleapis.com/v1beta/files

Parametri di query

pageSize integer

(Facoltativo) Numero massimo di File da restituire per pagina. Se non specificato, il valore predefinito è 10. Il valore massimo di pageSize è 100.

pageToken string

(Facoltativo) Un token di pagina di una chiamata files.list precedente.

Corpo della richiesta

Il corpo della richiesta deve essere vuoto.

Esempio di richiesta

Python

import google.generativeai as genai

print("My files:")
for f in genai.list_files():
    print("  ", f.name)

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const listFilesResponse = await fileManager.listFiles();

// View the response.
for (const file of listFilesResponse.files) {
  console.log(`name: ${file.name} | display name: ${file.displayName}`);
}

Vai

iter := client.ListFiles(ctx)
for {
	ifile, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(ifile.Name)
}

Conchiglia

echo "My files: "

curl "https://generativelanguage.googleapis.com/v1beta/files?key=$GOOGLE_API_KEY"

Corpo della risposta

Risposta per files.list.

In caso di esito positivo, il corpo della risposta contiene dati con la seguente struttura:

Campi
files[] object (File)

L'elenco di File.

nextPageToken string

Un token che può essere inviato come pageToken in una chiamata files.list successiva.

Rappresentazione JSON
{
  "files": [
    {
      object (File)
    }
  ],
  "nextPageToken": string
}

Metodo: files.delete

Consente di eliminare l'elemento File.

Endpoint

elimina https://generativelanguage.googleapis.com/v1beta/{name=files/*}

Parametri del percorso

name string

Obbligatorio. Il nome del File da eliminare. Esempio: files/abc-123 assume la forma files/{file}.

Corpo della richiesta

Il corpo della richiesta deve essere vuoto.

Esempio di richiesta

Python

import google.generativeai as genai

myfile = genai.upload_file(media / "poem.txt")

myfile.delete()

try:
    # Error.
    model = genai.GenerativeModel("gemini-1.5-flash")
    result = model.generate_content([myfile, "Describe this file."])
except google.api_core.exceptions.PermissionDenied:
    pass

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/jetpack.jpg`,
  {
    mimeType: "image/jpeg",
    displayName: "Jetpack drawing",
  },
);

// Delete the file.
await fileManager.deleteFile(uploadResult.file.name);

console.log(`Deleted ${uploadResult.file.displayName}`);

Vai

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "personWorkingOnComputer.jpg"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

gotFile, err := client.GetFile(ctx, file.Name)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Got file:", gotFile.Name)

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx,
	genai.FileData{URI: file.URI},
	genai.Text("Describe this image"))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

Conchiglia

curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name?key=$GOOGLE_API_KEY

Corpo della risposta

In caso di esito positivo, il corpo della risposta è vuoto.

Risorsa REST: files

Risorsa: file

Un file caricato nell'API.

Campi
name string

Immutabile. Identificatore. Il nome della risorsa File. L'ID (nome escluso il prefisso "files/") può contenere fino a 40 caratteri alfanumerici minuscoli o trattini (-). L'ID non può iniziare o terminare con un trattino. Se il nome è vuoto al momento della creazione, verrà generato un nome univoco. Esempio: files/123-456

displayName string

(Facoltativo) Il nome visualizzato leggibile per File. Il nome visualizzato non deve contenere più di 512 caratteri, spazi inclusi. Esempio: "Immagine di benvenuto"

mimeType string

Solo output. Tipo MIME del file.

sizeBytes string (int64 format)

Solo output. Dimensioni del file in byte.

createTime string (Timestamp format)

Solo output. Timestamp della creazione di File.

Un timestamp nel formato RFC3339 UTC "Zulu" con risoluzione in nanosecondi e fino a nove cifre frazionarie. Esempi: "2014-10-02T15:01:23Z" e "2014-10-02T15:01:23.045123456Z".

updateTime string (Timestamp format)

Solo output. Il timestamp dell'ultimo aggiornamento di File.

Un timestamp nel formato RFC3339 UTC "Zulu" con risoluzione in nanosecondi e fino a nove cifre frazionarie. Esempi: "2014-10-02T15:01:23Z" e "2014-10-02T15:01:23.045123456Z".

expirationTime string (Timestamp format)

Solo output. Timestamp di eliminazione di File. Imposta solo se la scadenza di File è programmata.

Un timestamp nel formato RFC3339 UTC "Zulu" con risoluzione in nanosecondi e fino a nove cifre frazionarie. Esempi: "2014-10-02T15:01:23Z" e "2014-10-02T15:01:23.045123456Z".

sha256Hash string (bytes format)

Solo output. Hash SHA-256 dei byte caricati.

Una stringa con codifica Base64.

uri string

Solo output. L'URI del File.

state enum (State)

Solo output. Stato di elaborazione del file.

error object (Status)

Solo output. Stato di errore se l'elaborazione del file non è riuscita.

Campo unione metadata. Metadati per il file. metadata può essere solo uno dei seguenti:
videoMetadata object (VideoMetadata)

Solo output. I metadati per un video.

Rappresentazione JSON
{
  "name": string,
  "displayName": string,
  "mimeType": string,
  "sizeBytes": string,
  "createTime": string,
  "updateTime": string,
  "expirationTime": string,
  "sha256Hash": string,
  "uri": string,
  "state": enum (State),
  "error": {
    object (Status)
  },

  // Union field metadata can be only one of the following:
  "videoMetadata": {
    object (VideoMetadata)
  }
  // End of list of possible types for union field metadata.
}

VideoMetadata

I metadati per un video File.

Campi
videoDuration string (Duration format)

Durata del video.

Una durata in secondi con un massimo di nove cifre frazionarie, che termina con "s". Esempio: "3.5s".

Rappresentazione JSON
{
  "videoDuration": string
}

Stato

Stati per il ciclo di vita di un file.

Enum
STATE_UNSPECIFIED Il valore predefinito. Questo valore viene utilizzato se lo stato viene omesso.
PROCESSING Il file è in fase di elaborazione e non può ancora essere utilizzato per l'inferenza.
ACTIVE Il file viene elaborato ed è disponibile per l'inferenza.
FAILED Elaborazione del file non riuscita.

Stato

Il tipo Status definisce un modello di errore logico adatto a diversi ambienti di programmazione, tra cui API REST e API RPC. Viene utilizzato da gRPC. Ogni messaggio Status contiene tre dati: codice di errore, messaggio di errore e dettagli dell'errore.

Per saperne di più su questo modello di errore e su come utilizzarlo, consulta la Guida alla progettazione dell'API.

Campi
code integer

Il codice di stato, che deve essere un valore enum di google.rpc.Code.

message string

Un messaggio di errore rivolto agli sviluppatori, che deve essere in inglese. Qualsiasi messaggio di errore rivolto agli utenti deve essere localizzato e inviato nel campo google.rpc.Status.details oppure localizzato dal cliente.

details[] object

Un elenco di messaggi con i dettagli dell'errore. Le API possono utilizzare un insieme comune di tipi di messaggi.

Un oggetto contenente campi di tipo arbitrario. Un campo aggiuntivo "@type" contiene un URI che identifica il tipo. Esempio: { "id": 1234, "@type": "types.example.com/standard/id" }.

Rappresentazione JSON
{
  "code": integer,
  "message": string,
  "details": [
    {
      "@type": string,
      field1: ...,
      ...
    }
  ]
}