File Upload Gateway
Master frontend upload, API orchestration, and cross-service communication with a production-ready multi-tier architecture
Success Response
{
"filename": "resume.pdf",
"size": 234567,
"contentType": "application/pdf",
"uploadedAt": "2025-01-15T10:30:00Z",
"storagePath": "/uploads/resume.pdf"
}Learning Objectives
A focused learning block for mastering file uploads and API orchestration without complex parsing or AI processing
Core Scope
- Upload file from React (PDF/DOCX/TXT)
- Send to Spring Boot orchestrator
- Forward to FastAPI for storage
- Return metadata (filename, size, type)
- End-to-end multipart handling
What You'll Learn
- Frontend file upload with FormData
- Multipart/form-data handling
- API orchestration patterns
- Cross-service communication
- Error handling and validation
Success Criteria
Complete end-to-end flow from browser to storage
Filename, size, and content type extracted
Focus on upload mechanics, not content processing
System Architecture
Learn how modern applications orchestrate file uploads across multiple services
React Frontend
Tier 1
Technologies
Responsibilities
- •File input and validation
- •Progress tracking
- •Error handling UI
- •Response display
Spring Boot Gateway
Tier 2
Technologies
Responsibilities
- •Receive multipart upload
- •Validate file type/size
- •Forward to FastAPI
- •Aggregate response
FastAPI Storage
Tier 3
Technologies
Responsibilities
- •Save file to disk
- •Extract metadata
- •Return storage info
- •Handle errors
Upload Flow
Step-by-step breakdown of the file upload journey through the system
React Upload
User selects file and clicks upload
POST /api/documentsFormData with multipart/form-data
Spring Boot Receives
Validates file and forwards to FastAPI
POST /ingest/fileMultipartFile → RestTemplate
FastAPI Saves
Stores file and extracts metadata
return metadataFilename, size, content type
Response Chain
Metadata flows back to React
200 OKComplete upload confirmation
React Upload Component
Learn how to handle file uploads in React with proper validation and error handling
File Input & Validation
const [file, setFile] = useState<File | null>(null)
const [uploading, setUploading] = useState(false)
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const selected = e.target.files?.[0]
if (!selected) return
// Validate file type
const allowed = ['application/pdf', 'application/vnd...']
if (!allowed.includes(selected.type)) {
alert('Only PDF, DOCX, TXT allowed')
return
}
// Validate file size (10MB max)
if (selected.size > 10 * 1024 * 1024) {
alert('File too large (max 10MB)')
return
}
setFile(selected)
}Upload with FormData
const handleUpload = async () => {
if (!file) return
setUploading(true)
const formData = new FormData()
formData.append('file', file)
try {
const response = await fetch('/api/documents', {
method: 'POST',
body: formData,
})
const result = await response.json()
console.log('Uploaded:', result)
alert(`Success: ${result.filename}`)
} catch (error) {
console.error('Upload failed:', error)
alert('Upload failed')
} finally {
setUploading(false)
}
}Key Learning Points
- •Use FormData for file uploads
- •Validate before upload
- •Handle loading states
- •Proper error handling
Spring Boot Orchestrator
Learn how to build an API gateway that orchestrates file uploads across services
REST Controller
@RestController
@RequestMapping("/api/documents")
public class DocumentController {
@Autowired
private RestTemplate restTemplate;
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Map<String, Object>> upload(
@RequestParam("file") MultipartFile file
) {
// Validate file
if (file.isEmpty()) {
return ResponseEntity.badRequest()
.body(Map.of("error", "No file provided"));
}
// Forward to FastAPI
String fastapiUrl = "http://localhost:8001/ingest/file";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body =
new LinkedMultiValueMap<>();
body.add("file", file.getResource());
HttpEntity<MultiValueMap<String, Object>> request =
new HttpEntity<>(body, headers);
ResponseEntity<Map> response =
restTemplate.postForEntity(fastapiUrl, request, Map.class);
return ResponseEntity.ok(response.getBody());
}
}Configuration
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
// application.properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
server.port=8080Add try-catch around RestTemplate calls
Check file type and size limits
Key Learning Points
- •MultipartFile handling in Spring Boot
- •RestTemplate for service-to-service calls
- •Proper HTTP headers for multipart
- •Configuration for file size limits
FastAPI File Receiver
Learn how to build a dedicated service for file storage and metadata extraction
Endpoint Implementation
from fastapi import FastAPI, File, UploadFile
from pathlib import Path
import shutil
app = FastAPI()
UPLOAD_DIR = Path("./uploads")
UPLOAD_DIR.mkdir(exist_ok=True)
@app.post("/ingest/file")
async def ingest_file(file: UploadFile = File(...)):
# Save file
file_path = UPLOAD_DIR / file.filename
with file_path.open("wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Get metadata
file_size = file_path.stat().st_size
return {
"filename": file.filename,
"size": file_size,
"contentType": file.content_type,
"storagePath": str(file_path)
}Error Handling
from fastapi import HTTPException
@app.post("/ingest/file")
async def ingest_file(file: UploadFile = File(...)):
try:
# Validate file type
allowed = ["application/pdf", "text/plain",
"application/vnd.openxmlformats..."]
if file.content_type not in allowed:
raise HTTPException(
status_code=400,
detail="Invalid file type"
)
# Save and return metadata
file_path = UPLOAD_DIR / file.filename
with file_path.open("wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {
"filename": file.filename,
"size": file_path.stat().st_size,
"contentType": file.content_type
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))Key Learning Points
- •UploadFile type in FastAPI
- •File I/O with shutil
- •Metadata extraction from files
- •Proper error handling with HTTPException
API Endpoints
Complete API contract for the file upload gateway system
/api/documentsUpload file from React frontend
→Request
multipart/form-data with 'file' field←Response
{ "filename": "...", "size": 12345, "contentType": "..." }/ingest/fileReceive and store file from Spring Boot
→Request
multipart/form-data forwarded from gateway←Response
{ "filename": "...", "size": 12345, "contentType": "...", "storagePath": "..." }Request Flow
React calls Spring Boot → Spring Boot validates and forwards to FastAPI → FastAPI saves and returns metadata → Response flows back through Spring Boot to React
Learning Outcomes
Build a solid foundation in file uploads and API orchestration
Learning Benefits
- Learn file upload mechanics without AI complexity
- Understand multipart/form-data handling
- Master cross-service communication patterns
- Build foundation for document processing systems
- Practice error handling at each tier
Definition of Done
- File successfully reaches FastAPI storage layer
- Metadata (filename, size, type) returned to React
- Proper validation at frontend and gateway
- Error handling implemented at all tiers
- Clean separation of concerns (upload → orchestrate → store)
Next Steps
After mastering the upload flow, you can extend this system to add document parsing, text extraction, AI processing, and more advanced features.
Build Your Next Product With AI Expertise
Experience the future of software development. Let our GenAI platform accelerate your next project.
Schedule a Free AI Blueprint Session