Saltar al contenido principal

Ejemplo básico

La forma más sencilla de usar Dropup.

Configuración mínima

import { useDropup } from '@samithahansaka/dropup';

function BasicUploader() {
const { files, getDropProps, getInputProps } = useDropup();

return (
<div
{...getDropProps()}
style={{
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center',
cursor: 'pointer',
}}
>
<input {...getInputProps()} />
<p>Arrastra archivos aquí o haz clic para seleccionar</p>

{files.length > 0 && (
<ul style={{ listStyle: 'none', padding: 0, marginTop: 20 }}>
{files.map(file => (
<li key={file.id}>
{file.name} ({(file.size / 1024).toFixed(1)} KB)
</li>
))}
</ul>
)}
</div>
);
}

Con funcionalidad de carga

import { useDropup } from '@samithahansaka/dropup';

function BasicUploadWithSubmit() {
const {
files,
actions,
state,
getDropProps,
getInputProps,
} = useDropup({
upload: {
url: '/api/upload',
method: 'POST',
},
});

return (
<div>
<div
{...getDropProps()}
style={{
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center',
}}
>
<input {...getInputProps()} />
<p>Suelta archivos aquí o haz clic para seleccionar</p>
</div>

{/* Lista de archivos */}
{files.length > 0 && (
<div style={{ marginTop: 20 }}>
<h3>Archivos seleccionados:</h3>
{files.map(file => (
<div
key={file.id}
style={{
display: 'flex',
justifyContent: 'space-between',
padding: 10,
borderBottom: '1px solid #eee',
}}
>
<span>{file.name}</span>
<span>{file.status}</span>
<button onClick={() => actions.remove(file.id)}>Eliminar</button>
</div>
))}
</div>
)}

{/* Botón de carga */}
<div style={{ marginTop: 20 }}>
<button
onClick={() => actions.upload()}
disabled={files.length === 0 || state.isUploading}
>
{state.isUploading ? `Cargando... ${state.progress}%` : 'Cargar todo'}
</button>

<button onClick={() => actions.reset()} style={{ marginLeft: 10 }}>
Limpiar todo
</button>
</div>
</div>
);
}

Carga de archivo único

import { useDropup } from '@samithahansaka/dropup';

function SingleFileUploader() {
const { files, getDropProps, getInputProps } = useDropup({
multiple: false, // Solo permite un archivo
maxFiles: 1,
});

const file = files[0];

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
{file ? (
<p>Seleccionado: {file.name}</p>
) : (
<p>Suelta un archivo aquí</p>
)}
</div>
);
}

const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
},
};

Con restricción de tipo de archivo

import { useDropup } from '@samithahansaka/dropup';

function ImageOnlyUploader() {
const { files, state, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
onValidationError: (errors) => {
errors.forEach(({ file }) => {
alert(`${file.name} no es una imagen válida`);
});
},
});

return (
<div
{...getDropProps()}
style={{
...styles.dropzone,
borderColor: state.isDragReject ? 'red' : '#ccc',
backgroundColor: state.isDragReject ? '#fff0f0' : 'white',
}}
>
<input {...getInputProps()} />
{state.isDragReject ? (
<p style={{ color: 'red' }}>¡Solo se aceptan imágenes!</p>
) : (
<p>Suelta imágenes aquí</p>
)}
</div>
);
}

Con callbacks

import { useDropup } from '@samithahansaka/dropup';

function UploaderWithCallbacks() {
const { files, actions, getDropProps, getInputProps } = useDropup({
upload: { url: '/api/upload' },

onFilesAdded: (newFiles) => {
console.log('Archivos agregados:', newFiles.map(f => f.name));
},

onUploadStart: (file) => {
console.log('Iniciando:', file.name);
},

onUploadProgress: (file, progress) => {
console.log(`${file.name}: ${progress}%`);
},

onUploadComplete: (file, response) => {
console.log('Completado:', file.name, file.uploadedUrl);
},

onUploadError: (file, error) => {
console.error('Falló:', file.name, error.message);
},

onAllComplete: (allFiles) => {
const successful = allFiles.filter(f => f.status === 'complete');
console.log(`¡Listo! ${successful.length}/${allFiles.length} exitosos`);
},
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Suelta archivos aquí</p>
</div>

<button onClick={() => actions.upload()}>
Cargar ({files.length} archivos)
</button>
</div>
);
}

Disparador de botón separado

import { useDropup } from '@samithahansaka/dropup';

function SeparateButtonUploader() {
const {
files,
openFileDialog,
getDropProps,
getInputProps,
} = useDropup();

return (
<div>
{/* Zona de soltar oculta que aún acepta archivos */}
<div
{...getDropProps()}
style={{
border: '2px dashed #ccc',
padding: 20,
marginBottom: 10,
}}
>
<input {...getInputProps()} />
<p>Suelta archivos aquí</p>
</div>

{/* Botón separado para abrir el diálogo de archivos */}
<button onClick={openFileDialog}>
Explorar archivos
</button>

{files.length > 0 && (
<p>{files.length} archivo(s) seleccionado(s)</p>
)}
</div>
);
}

Carga automática

import { useDropup } from '@samithahansaka/dropup';

function AutoUploader() {
const { files, getDropProps, getInputProps } = useDropup({
upload: { url: '/api/upload' },
autoUpload: true, // Los archivos se cargan automáticamente al agregarlos
onUploadComplete: (file) => {
console.log('Cargado:', file.uploadedUrl);
},
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Suelta archivos aquí - ¡se cargan automáticamente!</p>

{files.map(file => (
<div key={file.id}>
{file.name}:
{file.status === 'uploading' && ` ${file.progress}%`}
{file.status === 'complete' && ' ¡Listo!'}
{file.status === 'error' && ` Error: ${file.error?.message}`}
</div>
))}
</div>
);
}

Próximos pasos