Lesson 4 of 9
File Uploads - Images & Multipart
Uploading files from a mobile device requires picking from the gallery or camera, constructing a multipart/form-data request, and tracking progress. These steps differ significantly from web file uploads.
Image Upload with Progress
import * as ImagePicker from 'expo-image-picker';
import axios from 'axios';
import { useState } from 'react';
// npx expo install expo-image-picker
interface UploadResult { url: string; key: string; }
export function useImageUpload() {
const [progress, setProgress] = useState(0);
const [isUploading, setIsUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function pickAndUpload(): Promise<UploadResult | null> {
// 1. Request permission
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
setError('Media library permission denied');
return null;
}
// 2. Pick image
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1], // square crop
quality: 0.8, // compress to 80% - avoid sending 12MB HEIC files
});
if (result.canceled || !result.assets[0]) return null;
const asset = result.assets[0];
// 3. Build FormData
const formData = new FormData();
formData.append('file', {
uri: asset.uri,
type: asset.mimeType ?? 'image/jpeg',
name: asset.fileName ?? 'upload.jpg',
} as unknown as Blob);
formData.append('folder', 'avatars');
// 4. Upload with progress tracking
setIsUploading(true);
setProgress(0);
setError(null);
try {
const { data } = await apiClient.post<UploadResult>('/uploads', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
if (progressEvent.total) {
setProgress(Math.round((progressEvent.loaded / progressEvent.total) * 100));
}
},
});
return data;
} catch (err) {
setError('Upload failed - please try again');
return null;
} finally {
setIsUploading(false);
}
}
return { pickAndUpload, progress, isUploading, error };
}
// ---- Upload progress UI ----
function AvatarUploader() {
const { pickAndUpload, progress, isUploading } = useImageUpload();
const [avatarUri, setAvatarUri] = useState<string | null>(null);
async function handleUpload() {
const result = await pickAndUpload();
if (result) setAvatarUri(result.url);
}
return (
<View style={{ alignItems: 'center', gap: 16 }}>
{avatarUri ? (
<Image source={{ uri: avatarUri }} style={{ width: 80, height: 80, borderRadius: 40 }} />
) : (
<View style={{ width: 80, height: 80, borderRadius: 40, backgroundColor: '#1e293b', alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 32 }}>๐ค</Text>
</View>
)}
{isUploading && (
<View style={{ width: 200, height: 4, backgroundColor: '#1e293b', borderRadius: 2 }}>
<View style={{ width: `${progress}%`, height: 4, backgroundColor: '#229c6b', borderRadius: 2 }} />
</View>
)}
<Pressable onPress={handleUpload} disabled={isUploading} style={{ backgroundColor: '#229c6b', padding: 12, borderRadius: 8 }}>
<Text style={{ color: 'white', fontWeight: '700' }}>
{isUploading ? `Uploading ${progress}%` : 'Change Photo'}
</Text>
</Pressable>
</View>
);
}Tip
Tip
Practice File Uploads Images Multipart in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Uploading device photos with FormData and tracking real-time progress
Practice Task
Note
Practice Task - (1) Write a working example of File Uploads Images Multipart from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with File Uploads Images Multipart is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?