Angular 4与Ionic 3中File构造函数生成实例属性异常问题
Hey there, I’ve run into this exact quirk before—let’s break down why your File constructor is behaving so differently in Ionic 3 compared to plain Angular 4, and how to fix it.
The Root Cause
Ionic 3 ships with Cordova’s File plugin by default (or its type definitions are included in the project setup), and this plugin defines its own File interface that clashes with the browser’s native File object.
- In plain Angular 4, when you call
new File(...), you’re using the browser’s nativeFileclass (a subclass ofBlob), which has the expectedname,size,typeproperties, and stores content as a Blob. - In Ionic 3, the global
Filereference gets overridden by Cordova’sFiletype, which is designed for filesystem operations (not in-memory text files). This is why you’re seeing weird properties likelocalURLholding your filename, emptystart/end/sizevalues, and your text content stuck in an unexpected array.
Quick Fixes to Use the Native Browser File
Explicitly reference the browser’s
Fileviawindow
Bypass the Cordova-overriddenFileby directly callingwindow.File:// This uses the native browser File constructor, not Cordova's const textFile = new window.File(['Your text content here'], 'my-file.txt', { type: 'text/plain' });This will give you the same behavior as your Angular 4 project.
Fix TypeScript type errors (if needed)
If TypeScript complains thatwindow.Filedoesn’t exist, add this to yoursrc/typings.d.tsfile to extend the Window interface:interface Window { File: typeof File; }This tells TypeScript that
Fileis a valid property on the globalwindowobject.Verify the difference for yourself
Runconsole.log(File)in both your Angular 4 and Ionic 3 projects. You’ll see two completely different constructors:- Angular 4: Logs
function File() { [native code] }(the browser’s native implementation) - Ionic 3: Logs a Cordova-specific
Fileclass with methods likeresolveLocalFilesystemUrland a different property structure
- Angular 4: Logs
Why This Happens
Cordova’s File API is meant for interacting with device storage (like reading/writing files on the phone), while the browser’s native File is for in-memory file objects (often used with file input elements or Blob operations). Ionic’s setup prioritizes the Cordova API by default, which causes this overlap.
内容的提问来源于stack exchange,提问作者Josep Alacid

