Базовый пример
Самый простой способ использования Dropup.
Минимальная настройка
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>Перетащите файлы сюда или нажмите для выбора</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)} КБ)
</li>
))}
</ul>
)}
</div>
);
}
С функцией загрузки
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>Перетащите файлы сюда или нажмите для выбора</p>
</div>
{/* File List */}
{files.length > 0 && (
<div style={{ marginTop: 20 }}>
<h3>Выбранные файлы:</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)}>Удалить</button>
</div>
))}
</div>
)}
{/* Upload Button */}
<div style={{ marginTop: 20 }}>
<button
onClick={() => actions.upload()}
disabled={files.length === 0 || state.isUploading}
>
{state.isUploading ? `Загрузка... ${state.progress}%` : 'Загрузить все'}
</button>
<button onClick={() => actions.reset()} style={{ marginLeft: 10 }}>
Очистить все
</button>
</div>
</div>
);
}
Загрузка одного файла
import { useDropup } from '@samithahansaka/dropup';
function SingleFileUploader() {
const { files, getDropProps, getInputProps } = useDropup({
multiple: false, // Only allow one file
maxFiles: 1,
});
const file = files[0];
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
{file ? (
<p>Выбран: {file.name}</p>
) : (
<p>Перетащите файл сюда</p>
)}
</div>
);
}
const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
},
};
С ограничением типа файла
import { useDropup } from '@samithahansaka/dropup';
function ImageOnlyUploader() {
const { files, state, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
onValidationError: (errors) => {
errors.forEach(({ file }) => {
alert(`${file.name} не является допустимым изображением`);
});
},
});
return (
<div
{...getDropProps()}
style={{
...styles.dropzone,
borderColor: state.isDragReject ? 'red' : '#ccc',
backgroundColor: state.isDragReject ? '#fff0f0' : 'white',
}}
>
<input {...getInputProps()} />
{state.isDragReject ? (
<p style={{ color: 'red' }}>Принимаются только изображения!</p>
) : (
<p>Перетащите изображения сюда</p>
)}
</div>
);
}
С обработчиками событий
import { useDropup } from '@samithahansaka/dropup';
function UploaderWithCallbacks() {
const { files, actions, getDropProps, getInputProps } = useDropup({
upload: { url: '/api/upload' },
onFilesAdded: (newFiles) => {
console.log('Файлы добавлены:', newFiles.map(f => f.name));
},
onUploadStart: (file) => {
console.log('Начало загрузки:', file.name);
},
onUploadProgress: (file, progress) => {
console.log(`${file.name}: ${progress}%`);
},
onUploadComplete: (file, response) => {
console.log('Завершено:', file.name, file.uploadedUrl);
},
onUploadError: (file, error) => {
console.error('Ошибка:', file.name, error.message);
},
onAllComplete: (allFiles) => {
const successful = allFiles.filter(f => f.status === 'complete');
console.log(`Готово! ${successful.length}/${allFiles.length} успешно`);
},
});
return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Перетащите файлы сюда</p>
</div>
<button onClick={() => actions.upload()}>
Загрузить ({files.length} файлов)
</button>
</div>
);
}
Отдельная кнопка запуска
import { useDropup } from '@samithahansaka/dropup';
function SeparateButtonUploader() {
const {
files,
openFileDialog,
getDropProps,
getInputProps,
} = useDropup();
return (
<div>
{/* Hidden drop zone that still accepts drops */}
<div
{...getDropProps()}
style={{
border: '2px dashed #ccc',
padding: 20,
marginBottom: 10,
}}
>
<input {...getInputProps()} />
<p>Перетащите файлы сюда</p>
</div>
{/* Separate button to open file dialog */}
<button onClick={openFileDialog}>
Обзор файлов
</button>
{files.length > 0 && (
<p>Выбрано файлов: {files.length}</p>
)}
</div>
);
}
Автоматическая загрузка
import { useDropup } from '@samithahansaka/dropup';
function AutoUploader() {
const { files, getDropProps, getInputProps } = useDropup({
upload: { url: '/api/upload' },
autoUpload: true, // Files upload automatically when added
onUploadComplete: (file) => {
console.log('Загружено:', file.uploadedUrl);
},
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Перетащите файлы сюда - они загрузятся автоматически!</p>
{files.map(file => (
<div key={file.id}>
{file.name}:
{file.status === 'uploading' && ` ${file.progress}%`}
{file.status === 'complete' && ' Готово!'}
{file.status === 'error' && ` Ошибка: ${file.error?.message}`}
</div>
))}
</div>
);
}
Следующие шаги
- С предпросмотром - Показ предпросмотра изображений
- Зона перетаскивания - Пользовательские стилизованные зоны
- Загрузка по частям - Загрузка больших файлов по частям