Advanced Tutorial: File Uploads and Forms
Learn how to handle file uploads and form submissions in Hyperclay with progress tracking, drag-and-drop, and user feedback.
Core Concepts
File Upload with Progress
// Upload a file with progress tracking
await hyperclay.uploadFileBasic(file, {
onProgress: (percent) => {
progressBar.style.width = percent + '%';
},
onComplete: (result) => {
console.log('Uploaded:', result.url);
// Add image to gallery
gallery.innerHTML += `<img src="${result.url}">`;
},
onError: (error) => {
console.error('Upload failed:', error);
}
});
Drag and Drop
<div class="upload-zone"
ondrop="handleDrop(event)"
ondragover="event.preventDefault()">
Drag files here
</div>
<script>
async function handleDrop(event) {
event.preventDefault();
const files = event.dataTransfer.files;
for (const file of files) {
await hyperclay.uploadFile(file);
}
}
</script>
Contact Forms
// Send form data to site owner
async function handleSubmit(form) {
const data = getDataFromForm(form);
await hyperclay.sendMessage(data,
'Message sent successfully!',
() => form.reset()
);
}
Creating Files Programmatically
// Generate and save a JSON file
const data = { /* your data */ };
const result = await hyperclay.createFile({
fileName: 'backup.json',
fileBody: JSON.stringify(data)
});
console.log('File created:', result.url);
Advanced Patterns
Batch Upload
// Upload multiple files concurrently
const uploads = files.map(file =>
hyperclay.uploadFile(file)
);
const results = await Promise.all(uploads);
Image Resizing
// Resize before upload (pseudo-code)
const canvas = document.createElement('canvas');
// ... resize logic ...
const blob = await canvas.toBlob();
const resizedFile = new File([blob], 'image.jpg');
await hyperclay.uploadFile(resizedFile);
Form with Attachments
// Upload files, then send form with URLs
const attachments = [];
for (const file of files) {
const result = await hyperclay.uploadFile(file);
attachments.push(result.url);
}
formData.attachments = attachments;
await hyperclay.sendMessage(formData);
Export to CSV
// Generate CSV from DOM
const csv = /* generate CSV string */;
await hyperclay.createFile({
fileName: 'export.csv',
fileBody: csv
});
Best Practices
User Feedback
// Show progress
progressBar.style.width = percent + '%';
// Toast notifications
toast('Upload complete!');
toast('Error uploading', 'error');
Error Handling
try {
await hyperclay.uploadFile(file);
} catch (error) {
if (error.message.includes('size')) {
toast('File too large');
}
}
File Validation
if (file.size > 10 * 1024 * 1024) {
throw new Error('File too large');
}
if (!file.type.startsWith('image/')) {
throw new Error('Images only');
}
Mobile Support
<!-- Camera capture -->
<input type="file" accept="image/*" capture="environment">
Key Points
- File uploads only available to site owners
- Max file size: 10MB
- Files automatically scanned for security
- URLs are unique and unguessable
- Use
onbeforesave
for cleanup - Progress tracking available via callbacks
Last updated on