Ionic3使用cordova-plugin-file-transfer上传图片报错:Cannot read property 'constructor'
解决Ionic3中FileTransfer实例undefined导致的TypeError问题
从你的报错信息和使用的插件版本来看,核心问题是插件版本不兼容:你当前在用Ionic3框架,却安装了适配Ionic4+的@ionic-native/file-transfer@5.0.0,这个版本的插件依赖体系和Ionic3不匹配,导致FileTransfer服务没有被正确注入,调用this.transfer.create()时自然会出现Cannot read property 'constructor' of undefined的错误。
下面是具体的修复步骤:
1. 降级@ionic-native/file-transfer到适配Ionic3的版本
Ionic3对应使用@ionic-native/file-transfer的4.x版本,执行以下命令替换当前版本:
npm uninstall @ionic-native/file-transfer npm install @ionic-native/file-transfer@4.x --save
2. 确认AppModule中正确注册FileTransfer服务
在Ionic3中,所有Native插件服务都需要手动添加到app.module.ts的providers数组里,不能用Ionic4+的providedIn: 'root'自动注册方式。检查你的app.module.ts:
import { FileTransfer } from '@ionic-native/file-transfer'; @NgModule({ ... providers: [ ... FileTransfer, // 务必确保这里添加了该服务 ... ] }) export class AppModule {}
3. 确保在平台就绪后执行上传逻辑
Cordova插件必须等平台完全初始化才能正常工作,所以建议把拍照和上传的逻辑包裹在platform.ready()中:
修改你的component.ts中的takePicture方法:
import { Platform } from 'ionic-angular'; // 构造函数注入Platform服务 constructor(private platform: Platform, ...) {} takePicture() { this.platform.ready().then(() => { const options: CameraOptions = { quality: 50, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, targetWidth: 500, targetHeight: 500, saveToPhotoAlbum: false }; this.camera.getPicture(options) .then((imageData) => this._img.uploadImage(imageData)) .catch(err => console.log(err)); }); }
4. 验证插件安装状态并清理构建缓存
- 检查cordova-plugin-file-transfer是否正常安装:
cordova plugin list
如果列表里没有cordova-plugin-file-transfer 1.7.1,重新安装该插件:
cordova plugin add cordova-plugin-file-transfer@1.7.1
- 清理Android构建缓存并重新构建项目:
ionic cordova clean android ionic cordova build android
完成以上步骤后重新运行项目,应该就能解决FileTransfer实例未定义的问题了。
内容的提问来源于stack exchange,提问作者poimsm2
相关产品推荐
相关产品推荐

