转换图片文件为Blob时触发SECURITY_ERR(code:2),求原因及替代方法
Fixing SECURITY_ERR When Converting Images to Blob in Cordova
Hey there, let's break down why you're hitting that SECURITY_ERR and get your blob conversion working smoothly—plus cover alternatives that fit your API's Binary/Multipart requirements.
Why You're Seeing the SECURITY_ERR
That error almost always ties to file permission issues or unsafe path handling in Cordova:
- Missing app permissions: Your app might not have explicit access to read external storage (Android) or the photo library (iOS).
- Manual path manipulation: Splitting the
nativeURLmanually can lead to accessing restricted paths outside your app's sandbox, triggering security restrictions. - Outdated plugins: Older versions of
cordova-plugin-fileorcordova-plugin-filechoosersometimes have permission-related bugs that cause this error.
Alternative Blob Conversion Method (More Reliable)
Instead of parsing paths manually and using readAsArrayBuffer with a constructed directory URL, use the FileEntry object directly to get a File instance, then use FileReader to convert it to an ArrayBuffer/Blob. This avoids path-related security pitfalls entirely.
Here's a revised version of your code:
choose() { this.filechooser.open().then((uri) => { this.file.resolveLocalFilesystemUrl(uri).then((fileEntry) => { // Get the File object directly from the FileEntry (Cordova's recommended approach) fileEntry.file((file) => { const reader = new FileReader(); reader.onloadend = () => { // Convert the ArrayBuffer result to a Blob const blob = new Blob([reader.result], { type: file.type || "image/jpeg" }); alert('blob creation success'); // Handle your API's requirements right away: // 1. For Binary type: Use reader.result directly (it's already an ArrayBuffer) // const binaryData = reader.result; // 2. For Multipart type: Wrap the Blob in FormData const formData = new FormData(); formData.append('attachment', blob, file.name); // Use this formData object in your API request }; reader.onerror = (error) => { alert('FileReader Error: ' + JSON.stringify(error)); }; // Read the file content as an ArrayBuffer reader.readAsArrayBuffer(file); }, (error) => { alert('Failed to access file: ' + JSON.stringify(error)); }); }, (error) => { alert('Error resolving file URL: ' + JSON.stringify(error)); }); }, (error) => { alert('Error choosing file: ' + JSON.stringify(error)); }); }
Key Improvements in This Approach
- Uses Cordova's native file access:
fileEntry.file()is the secure, supported way to access file content, avoiding manual path errors. - Dynamic MIME type: Uses the file's native
typeinstead of hardcoding "image/jpeg" (works for PNG, GIF, etc.). - Built-in support for your API needs:
- Binary:
reader.resultis an ArrayBuffer, which is a valid binary format for most APIs. - Multipart: Wrapping the Blob in
FormDataautomatically formats it asmultipart/form-data, which your API accepts.
- Binary:
Additional Steps to Fix SECURITY_ERR
- Verify Permissions:
- For Android: Add these lines to your
config.xml:<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> - For iOS: Add this to your
info.plist(via config.xml or Xcode) to explain why you need photo library access:<edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge"> <string>Need access to photos to upload images</string> </edit-config>
- For Android: Add these lines to your
- Update Plugins:
Run these commands to ensure you're using the latest, most stable versions:cordova plugin update cordova-plugin-file cordova plugin update cordova-plugin-filechooser
内容的提问来源于stack exchange,提问作者shiben
相关产品推荐
相关产品推荐

