Sdílet prostřednictvím


Ukládání dat do položky

Každá položka Fabric má přístup k úložišti OneLake, které poskytuje zabezpečený a škálovatelný způsob ukládání souborů spojených s vaší položkou. Tento průvodce vysvětluje, jak nahrát soubory do položky Fabric pomocí FabricPlatformAPIClient a podkladového OneLakeClient.

Porozumění ukládání položek v systému Fabric

Každá položka ve Fabric má v OneLake vlastní vyhrazenou oblast úložiště. Toto úložiště je uspořádané do složek s hlavními složkami:

  • Soubory – ukládání obecných souborů a dokumentů
  • Tabulky – pro ukládání dat tabulky

Požadavky

Před nahráním souborů do položky potřebujete:

  • Platný pracovní prostor Fabric
  • Existující položka, do které chcete soubor nahrát
  • Příslušná oprávnění k zápisu do položky

Vytvoření objektu FabricPlatformAPIClient

Nejprve vytvořte FabricPlatformAPIClient instanci:

import { getWorkloadClient } from "../controller/WorkloadClient";
import { FabricPlatformAPIClient } from "../clients/FabricPlatformAPIClient";

// Create client using the current user's context
const fabricClient = FabricPlatformAPIClient.create(getWorkloadClient());

Příklad: Nahrání textového souboru do položky

Tady je postup, jak nahrát textový soubor do položky pomocí klienta OneLake:

async function uploadTextFileToItem(
  workspaceId: string, 
  itemId: string, 
  fileName: string, 
  content: string
) {
  try {
    // Get the FabricPlatformAPIClient
    const fabricClient = FabricPlatformAPIClient.create(getWorkloadClient());
    
    // Access the OneLake client
    const oneLakeClient = fabricClient.oneLake;
    
    // Generate the file path in OneLake for this item
    // This follows the pattern: workspaceId/itemId/Files/fileName
    const filePath = oneLakeClient.constructor.getFilePath(workspaceId, itemId, fileName);
    
    // Write the text content to the file
    await oneLakeClient.writeFileAsText(filePath, content);
    
    console.log(`Successfully uploaded ${fileName} to item ${itemId}`);
    return true;
  } catch (error) {
    console.error("Error uploading file to item:", error);
    throw error;
  }
}

Příklad: Nahrání binárního souboru do položky

U binárních souborů, jako jsou obrázky nebo soubory PDF, musíte nejprve převést soubor na base64:

async function uploadBinaryFileToItem(
  workspaceId: string,
  itemId: string,
  fileName: string,
  fileData: ArrayBuffer // Binary file data
) {
  try {
    const fabricClient = FabricPlatformAPIClient.create(getWorkloadClient());
    const oneLakeClient = fabricClient.oneLake;
    
    // Convert binary data to base64
    const base64Content = arrayBufferToBase64(fileData);
    
    // Generate the file path
    const filePath = oneLakeClient.constructor.getFilePath(workspaceId, itemId, fileName);
    
    // Write the binary content to the file
    await oneLakeClient.writeFileAsBase64(filePath, base64Content);
    
    console.log(`Successfully uploaded binary file ${fileName} to item ${itemId}`);
    return true;
  } catch (error) {
    console.error("Error uploading binary file to item:", error);
    throw error;
  }
}

// Helper function to convert ArrayBuffer to base64
function arrayBufferToBase64(buffer: ArrayBuffer): string {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  
  return btoa(binary);
}

Příklad: Nahrání souboru z prohlížeče

Pokud vytváříte webové rozhraní, můžete pomocí této funkce zpracovat upload souborů ze souborového pole:

async function handleFileUpload(
  workspaceId: string,
  itemId: string,
  fileInputElement: HTMLInputElement
) {
  if (!fileInputElement.files || fileInputElement.files.length === 0) {
    console.warn("No file selected");
    return false;
  }
  
  const file = fileInputElement.files[0];
  const fileName = file.name;
  
  try {
    // Read the file as ArrayBuffer
    const fileBuffer = await readFileAsArrayBuffer(file);
    
    // Upload based on file type
    if (file.type.startsWith('text/')) {
      // For text files, convert to string and upload as text
      const textDecoder = new TextDecoder();
      const textContent = textDecoder.decode(fileBuffer);
      
      return await uploadTextFileToItem(workspaceId, itemId, fileName, textContent);
    } else {
      // For binary files, upload as base64
      return await uploadBinaryFileToItem(workspaceId, itemId, fileName, fileBuffer);
    }
  } catch (error) {
    console.error("Error processing file upload:", error);
    throw error;
  }
}

// Helper function to read file as ArrayBuffer
function readFileAsArrayBuffer(file: File): Promise<ArrayBuffer> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as ArrayBuffer);
    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
}

Správa souborů v položce

Po nahrání souborů můžete také:

Kontrola, jestli soubor existuje

async function checkFileExists(workspaceId: string, itemId: string, fileName: string) {
  const fabricClient = FabricPlatformAPIClient.create(getWorkloadClient());
  const filePath = fabricClient.oneLake.constructor.getFilePath(workspaceId, itemId, fileName);
  
  return await fabricClient.oneLake.checkIfFileExists(filePath);
}

Čtení obsahu souboru

async function readTextFile(workspaceId: string, itemId: string, fileName: string) {
  const fabricClient = FabricPlatformAPIClient.create(getWorkloadClient());
  const filePath = fabricClient.oneLake.constructor.getFilePath(workspaceId, itemId, fileName);
  
  return await fabricClient.oneLake.readFileAsText(filePath);
}

Odstranění souboru

async function deleteFile(workspaceId: string, itemId: string, fileName: string) {
  const fabricClient = FabricPlatformAPIClient.create(getWorkloadClient());
  const filePath = fabricClient.oneLake.constructor.getFilePath(workspaceId, itemId, fileName);
  
  await fabricClient.oneLake.deleteFile(filePath);
  console.log(`File ${fileName} deleted successfully`);
}

Osvědčené postupy pro nahrávání souborů

  1. Použijte vhodné formáty souborů: Zvažte účel souboru a použijte formáty, které jsou široce podporované.
  2. Řádně zpracovávat chyby: Vždy zahrňte zpracování chyb při problémech se sítí nebo ohledně oprávnění.
  3. Ověřte velikosti souborů: Nahrávání a zpracování velkých souborů může trvat déle.
  4. Zkontrolovat oprávnění: Před pokusem o nahrání se ujistěte, že má uživatel příslušná oprávnění.
  5. Používejte předpony souborů nebo složky: U složitých položek s mnoha soubory zvažte jejich uspořádání do podsložek.

Použití OneLakeClientItemWrapperu

Pro zjednodušený přístup k souborům položek můžete použít OneLakeClientItemWrapper:

async function uploadFileWithItemWrapper(item, fileName, content) {
  const fabricClient = FabricPlatformAPIClient.create(getWorkloadClient());
  
  // Create a wrapper for simpler access to this specific item
  const itemWrapper = fabricClient.oneLake.createItemWrapper({
    workspaceId: item.workspaceId,
    itemId: item.id
  });
  
  // Upload directly to the item (no need to specify paths)
  await itemWrapper.writeFileAsText(fileName, content);
  
  // Read the file back
  const fileContent = await itemWrapper.readFileAsText(fileName);
  
  console.log(`File uploaded and read back: ${fileContent.substring(0, 50)}...`);
}

Tento zabalovač zjednodušuje operace se soubory tím, že automaticky zpracovává sestavení celé cesty.