Subida de archivos

Gestione la subida de archivos con Supabase Storage.

Nota: Este es contenido de ejemplo/marcador de posición con fines de demostración.

Permita que los usuarios suban y gestionen archivos con Supabase Storage.

Configuración

Crear un bucket de almacenamiento

-- Crear un bucket público para los avatares
INSERT INTO storage.buckets (id, name, public)
VALUES ('avatars', 'avatars', true);

-- Crear un bucket privado para los documentos
INSERT INTO storage.buckets (id, name, public)
VALUES ('documents', 'documents', false);

Definir las políticas de almacenamiento

-- Permitir que los usuarios suban sus propios avatares
CREATE POLICY "Users can upload their own avatar"
ON storage.objects FOR INSERT
WITH CHECK (
  bucket_id = 'avatars' AND
  auth.uid()::text = (storage.foldername(name))[1]
);

-- Permitir que los usuarios vean sus propios avatares
CREATE POLICY "Users can view their own avatar"
ON storage.objects FOR SELECT
USING (
  bucket_id = 'avatars' AND
  auth.uid()::text = (storage.foldername(name))[1]
);

-- Permitir que los usuarios eliminen sus propios avatares
CREATE POLICY "Users can delete their own avatar"
ON storage.objects FOR DELETE
USING (
  bucket_id = 'avatars' AND
  auth.uid()::text = (storage.foldername(name))[1]
);

Componente de subida

Subida de archivos básica

'use client';

import { useState } from 'react';
import { uploadFileAction } from '../_lib/actions';

export function FileUpload() {
  const [uploading, setUploading] = useState(false);
  const [file, setFile] = useState<File | null>(null);

  const handleUpload = async () => {
    if (!file) return;

    setUploading(true);

    const formData = new FormData();
    formData.append('file', file);

    const result = await uploadFileAction(formData);

    if (result.success) {
      toast.success('File uploaded successfully');
    }

    setUploading(false);
  };

  return (
    <div>
      <input
        type="file"
        onChange={(e) => setFile(e.files?.[0] || null)}
        accept="image/*"
      />
      <button
        onClick={handleUpload}
        disabled={!file || uploading}
      >
        {uploading ? 'Uploading...' : 'Upload'}
      </button>
    </div>
  );
}

Server Action

'use server';

import { enhanceAction } from '@kit/next/actions';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

export const uploadFileAction = enhanceAction(
  async (formData: FormData, user) => {
    const file = formData.get('file') as File;

    if (!file) {
      throw new Error('No file provided');
    }

    const client = getSupabaseServerClient();
    const fileExt = file.name.split('.').pop();
    const fileName = `${user.id}/${Date.now()}.${fileExt}`;

    const { data, error } = await client.storage
      .from('avatars')
      .upload(fileName, file, {
        cacheControl: '3600',
        upsert: false,
      });

    if (error) throw error;

    // Obtener la URL pública
    const { data: { publicUrl } } = client.storage
      .from('avatars')
      .getPublicUrl(fileName);

    return {
      success: true,
      url: publicUrl,
      path: data.path,
    };
  },
  { auth: true }
);

Subida mediante arrastrar y soltar

'use client';

import { useCallback } from 'react';
import { useDropzone } from 'react-dropzone';

export function DragDropUpload() {
  const onDrop = useCallback(async (acceptedFiles: File[]) => {
    for (const file of acceptedFiles) {
      const formData = new FormData();
      formData.append('file', file);
      await uploadFileAction(formData);
    }
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'image/*': ['.png', '.jpg', '.jpeg', '.gif'],
    },
    maxSize: 5 * 1024 * 1024, // 5 MB
  });

  return (
    <div
      {...getRootProps()}
      className={cn(
        'border-2 border-dashed rounded-lg p-8 text-center cursor-pointer',
        isDragActive && 'border-primary bg-primary/10'
      )}
    >
      <input {...getInputProps()} />
      {isDragActive ? (
        <p>Drop files here...</p>
      ) : (
        <p>Drag and drop files here, or click to select</p>
      )}
    </div>
  );
}

Validación de archivos

Validación en el cliente

function validateFile(file: File) {
  const maxSize = 5 * 1024 * 1024; // 5 MB
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

  if (file.size > maxSize) {
    throw new Error('File size must be less than 5MB');
  }

  if (!allowedTypes.includes(file.type)) {
    throw new Error('File type must be JPEG, PNG, or GIF');
  }

  return true;
}

Validación en el servidor

export const uploadFileAction = enhanceAction(
  async (formData: FormData, user) => {
    const file = formData.get('file') as File;

    // Validar el tamaño del archivo
    if (file.size > 5 * 1024 * 1024) {
      throw new Error('File too large');
    }

    // Validar el tipo de archivo
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
      throw new Error('Invalid file type');
    }

    // Validar las dimensiones de las imágenes
    if (file.type.startsWith('image/')) {
      const dimensions = await getImageDimensions(file);
      if (dimensions.width > 4000 || dimensions.height > 4000) {
        throw new Error('Image dimensions too large');
      }
    }

    // Continuar con la subida...
  },
  { auth: true }
);

Optimización de imágenes

Redimensionar al subir

import sharp from 'sharp';

export const uploadAvatarAction = enhanceAction(
  async (formData: FormData, user) => {
    const file = formData.get('file') as File;
    const buffer = Buffer.from(await file.arrayBuffer());

    // Redimensionar la imagen
    const resized = await sharp(buffer)
      .resize(200, 200, {
        fit: 'cover',
        position: 'center',
      })
      .jpeg({ quality: 90 })
      .toBuffer();

    const client = getSupabaseServerClient();
    const fileName = `${user.id}/avatar.jpg`;

    const { error } = await client.storage
      .from('avatars')
      .upload(fileName, resized, {
        contentType: 'image/jpeg',
        upsert: true,
      });

    if (error) throw error;

    return { success: true };
  },
  { auth: true }
);

Seguimiento del progreso

'use client';

import { useState } from 'react';

export function UploadWithProgress() {
  const [progress, setProgress] = useState(0);

  const handleUpload = async (file: File) => {
    const client = getSupabaseBrowserClient();

    const { error } = await client.storage
      .from('documents')
      .upload(`uploads/${file.name}`, file, {
        onUploadProgress: (progressEvent) => {
          const percent = (progressEvent.loaded / progressEvent.total) * 100;
          setProgress(Math.round(percent));
        },
      });

    if (error) throw error;
  };

  return (
    <div>
      <input type="file" onChange={(e) => handleUpload(e.target.files![0])} />
      {progress > 0 && (
        <div className="w-full bg-gray-200 rounded-full h-2">
          <div
            className="bg-primary h-2 rounded-full transition-all"
            style={{ width: `${progress}%` }}
          />
        </div>
      )}
    </div>
  );
}

Descarga de archivos

Obtener la URL pública

const { data } = client.storage
  .from('avatars')
  .getPublicUrl('user-id/avatar.jpg');

console.log(data.publicUrl);

Descargar un archivo privado

const { data, error } = await client.storage
  .from('documents')
  .download('private-file.pdf');

if (data) {
  const url = URL.createObjectURL(data);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'file.pdf';
  a.click();
}

Generar una URL firmada

const { data, error } = await client.storage
  .from('documents')
  .createSignedUrl('private-file.pdf', 3600); // 1 hora

console.log(data.signedUrl);

Eliminación de archivos

export const deleteFileAction = enhanceAction(
  async (data, user) => {
    const client = getSupabaseServerClient();

    const { error } = await client.storage
      .from('avatars')
      .remove([data.path]);

    if (error) throw error;

    return { success: true };
  },
  {
    schema: z.object({
      path: z.string(),
    }),
    auth: true,
  }
);

Buenas prácticas

  1. Valide en ambos lados - En el cliente y en el servidor
  2. Limite el tamaño de los archivos - Evite abusos
  3. Sanee los nombres de archivo - Elimine los caracteres especiales
  4. Use nombres únicos - Evite colisiones
  5. Optimice las imágenes - Redimensiónelas antes de subirlas
  6. Defina políticas de almacenamiento - Controle el acceso
  7. Supervise el uso - Haga un seguimiento de los costes de almacenamiento
  8. Elimine los archivos sin usar - Mantenimiento periódico
  9. Use una CDN - Para los archivos públicos
  10. Implemente un análisis antivirus - Para los archivos subidos por los usuarios