Here’s a comprehensive solution addressing all three aspects - CORS preflight handling, hybrid mobile WebView quirks, and REST API file upload architecture:
1. CORS Preflight Handling:
Create a custom Java action to handle OPTIONS requests:
// CustomCORSHandler.java
public void handlePreflight(IContext context, IMendixObject request) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
response.setHeader("Access-Control-Max-Age", "86400");
}
Add this to your REST service before-microflow to intercept OPTIONS requests.
2. Hybrid Mobile WebView Solution:
The key issue is that WebViews use file:// or http://localhost origins which trigger CORS. Instead of fighting this, implement a two-stage upload:
// Mobile app - convert to base64 first
const base64File = await convertToBase64(fileObject);
mx.data.action({
params: { fileData: base64File, fileName: file.name },
callback: function(result) { /* handle success */ }
});
This bypasses CORS entirely by using Mendix’s native data actions instead of direct REST calls.
3. REST API File Upload (for external integrations):
For external systems that must use REST, implement multipart/form-data handling:
// FileUploadHandler microflow
List<IMendixObject> files = Core.retrieveXPathQuery(context,
"//System.FileDocument[Name=$fileName]");
if (files.isEmpty()) {
FileDocument doc = new FileDocument(context);
Core.storeFileDocumentContent(context, doc.getMendixObject(), inputStream);
}
4. Chunked Upload for Large Files:
For files >5MB, implement chunked upload with resume capability:
- Client sends file in 1MB chunks with chunk index
- Server stores chunks temporarily with unique upload ID
- Final request assembles chunks into complete file
- Handles network interruptions gracefully
5. Configuration Steps:
- Set
Access-Control-Allow-Origin to your mobile app’s domain (use wildcard only for development)
- Enable
Access-Control-Allow-Credentials if using authentication tokens
- For iOS WebView, ensure SSL certificates are valid (self-signed certs fail)
- Add timeout handling - mobile networks can be unreliable
Performance Considerations:
The base64 approach adds ~33% size overhead, but eliminates CORS complexity. For production with many large files, consider:
- Direct S3/Azure Blob upload with pre-signed URLs
- Background upload queue for offline capability
- Compression before upload (images especially)
This architecture has worked reliably across iOS 12+, Android 8+, and all modern browsers. The key is avoiding direct REST calls from WebView contexts and using Mendix’s native communication layer instead.