Ionic/Cordova读取应用文件失败:遇URI格式错误问题求助
Hey there, I’ve dealt with this exact error a few times when working with Ionic Cordova in the browser—let’s break down what’s going wrong and how to fix it.
Common Causes & Solutions
1. Fix Path Formatting Issues
The "malformed URI" error usually comes from incorrect path concatenation. In the Cordova browser platform, this.file.applicationDirectory points to the www folder of your built project (e.g., file:///path/to/your-app/platforms/browser/www/). If you’re adding a trailing slash or missing one when appending assets/data/your-file.txt, you’ll end up with invalid paths like file:///.../www//assets/data/... (double slashes) or file:///.../wwwassets/data/... (missing slash).
Fix: Normalize the path before using it:
// Remove trailing slash from applicationDirectory if present const baseDir = this.file.applicationDirectory.replace(/\/$/, ''); const filePath = `${baseDir}/assets/data/your-file.txt`;
2. Avoid readAsDataURL for Large Files
The "Data URL length exceeded" error happens when you use readAsDataURL() on a large file—base64 encoding bloats the file size by ~33%, which can easily hit browser limits. Since you’re working with text files, switch to readAsText() instead—it returns the raw text directly without generating a Data URL.
Working Code Example with Cordova File Plugin:
import { File } from '@ionic-native/file/ngx'; constructor(private file: File) {} async loadTextFile() { try { // Read directly using relative path within applicationDirectory const content = await this.file.readAsText( this.file.applicationDirectory, 'assets/data/your-file.txt' ); console.log('File content:', content); } catch (err) { console.error('File read error:', err); } }
3. Verify Files Are Copied to the Browser Platform
Sometimes the assets/data folder doesn’t get synced to the platforms/browser/www/assets directory during build. Run this command to ensure all assets are properly copied:
ionic cordova prepare browser
Then manually check platforms/browser/www/assets/data to confirm your text files are present.
4. Use Fetch API as a Browser-Specific Alternative
For the browser platform, you don’t even need the Cordova File Plugin—just use the native Fetch API, which works directly with relative paths since the www folder acts as your web root:
async loadFileWithFetch() { try { const response = await fetch('assets/data/your-file.txt'); const content = await response.text(); console.log('Fetched content:', content); } catch (err) { console.error('Fetch error:', err); } }
This method is often more reliable for browser debugging and avoids Cordova-specific path quirks.
Quick Recap
- Double-check path concatenation to avoid malformed URIs
- Replace
readAsDataURL()withreadAsText()for text files to bypass Data URL limits - Ensure assets are synced to the browser platform with
ionic cordova prepare browser - Use Fetch API as a simpler alternative for browser-only testing
内容的提问来源于stack exchange,提问作者Anthony O.

