Ionic 2:拍摄/选择图片无法显示问题及双方式上传需求求助
解决Ionic 2图片上传后不显示&拍摄照片展示问题
我来帮你搞定这个图片显示的问题,顺便把拍摄照片的展示逻辑梳理清楚~
一、核心问题分析
你当前的<img>标签绑定的是服务器接口地址,但刚选择/拍摄的图片还没上传到服务器,页面自然不会更新显示。咱们得先在本地临时展示选中的图片,上传成功后再同步更新服务器地址的src。
二、修改代码实现完整功能
1. 更新profile.html
添加本地图片临时展示的逻辑,优先显示本地选中的图片,无本地图片时再加载服务器资源:
<img class="profile-picture" [src]="localImageUrl ? localImageUrl : (baseUrl + 'service/renderImage/' + profId)" (click)="changePicture()"> <h6 secondary>{{ 'TAP_ON_IMAGE' | translate }}</h6>
2. 完善profile.ts的逻辑
实现弹出选择器(相册/相机)、获取图片路径、临时展示、上传服务器的完整流程:
import { Component } from '@angular/core'; import { Camera, CameraOptions, ActionSheetController } from 'ionic-angular'; import { Transfer, TransferObject } from '@ionic-native/transfer'; @Component({ selector: 'page-profile', templateUrl: 'profile.html' }) export class ProfilePage { localImageUrl: string; baseUrl: string = '你的服务器基础地址'; // 替换成实际地址 profId: string = '当前用户ID'; // 替换成实际用户ID constructor( private camera: Camera, private actionSheetCtrl: ActionSheetController, private transfer: Transfer ) {} changePicture() { let actionSheet = this.actionSheetCtrl.create({ title: '选择图片来源', buttons: [ { text: '从相册选择', handler: () => { this.getPicture(this.camera.PictureSourceType.PHOTOLIBRARY); } }, { text: '拍照', handler: () => { this.getPicture(this.camera.PictureSourceType.CAMERA); } }, { text: '取消', role: 'cancel' } ] }); actionSheet.present(); } getPicture(sourceType: number) { const options: CameraOptions = { quality: 80, sourceType: sourceType, destinationType: this.camera.DestinationType.FILE_URI, // 获取本地文件路径 encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, allowEdit: true, correctOrientation: true }; this.camera.getPicture(options).then((imagePath) => { // 立刻在页面展示本地图片 this.localImageUrl = imagePath; // 可选:上传图片到服务器 this.uploadToServer(imagePath); }, (err) => { console.log('获取图片失败:', err); }); } uploadToServer(imagePath: string) { const fileTransfer: TransferObject = this.transfer.create(); const uploadUrl = this.baseUrl + 'service/uploadImage/' + this.profId; // 你的上传接口 const uploadOptions = { fileKey: 'profilePic', // 对应后端接收的文件字段名 fileName: 'profile.jpg', chunkedMode: false, mimeType: 'image/jpeg' }; fileTransfer.upload(imagePath, uploadUrl, uploadOptions).then((data) => { console.log('上传成功:', data); // 上传成功后,清除本地路径,让页面重新加载服务器最新图片 this.localImageUrl = null; // 可选:加时间戳避免缓存问题 // this.localImageUrl = this.baseUrl + 'service/renderImage/' + this.profId + '?t=' + new Date().getTime(); }, (err) => { console.log('上传失败:', err); }); } }
三、关键注意事项
- 本地图片展示:通过
destinationType: FILE_URI获取图片的本地文件路径,直接绑定到localImageUrl,就能立刻看到选中/拍摄的照片。 - 缓存问题处理:如果上传后服务器图片更新但页面显示旧图,可在服务器地址后加时间戳参数,强制浏览器刷新资源。
- 插件配置:确保已经安装并在
app.module.ts中导入配置@ionic-native/camera和@ionic-native/transfer插件。
四、拍摄照片的展示说明
上面的代码已经包含了拍摄照片的展示逻辑:选择“拍照”选项后,调用相机获取图片本地路径,赋值给localImageUrl,页面上的<img>就会自动显示刚拍摄的照片。如果需要永久保存,上传到服务器后再切换回服务器地址即可。
内容的提问来源于stack exchange,提问作者Abdul khader
相关产品推荐
相关产品推荐

