ionic3 FileTransfer 照片上传前后端

最近在做图片上传功能遇到不少坑,再此记录避免大家少踩坑。

百度FileTransfer文件上传没有一个完整的前后端栗子,这里前后端都记录下,后端采用WCF
废话就不多说了直接上代码

前端

1. CameraServiceProvider.ts 这是一个服务

/**
  * 打开相机,返回文件路径
  */
  openCamera(cameraOptions: any): Promise<any> {
    return new Promise((resolve, reject) => {
      const options: CameraOptions = cameraOptions;
      this.camera.getPicture(options).then((imageData) => {
        console.log("got file: " + imageData);
        // If it's base64:
        imageData = 'data:image/jpeg;base64,' + imageData;
        resolve(imageData);
      }, (err) => {
        // Handle error
        reject(err);
      });
    });
  }

2. 上传页面

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, LoadingController, Loading } from 'ionic-angular';
import { PhotoViewer } from '@ionic-native/photo-viewer';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { Camera } from '@ionic-native/camera';
import { MyApp } from '../../app/app.component';
import { CameraServiceProvider } from '../../providers/camera-service/camera-service';
import { SqliteServiceProvider } from '../../providers/sqlite-service/sqlite-service';
/**
* Generated class for the InspectionPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
  selector: 'page-inspection',
  templateUrl: 'inspection.html',
})

export class InspectionPage {
  item: any;
  username: string;
  ID: any;
  CheckValue: any;
  Remark: any;
  loading: Loading;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private camera: Camera,
    private file: File,
    private transfer: FileTransfer,
    private photoViewer: PhotoViewer,
    private toastCtrl: ToastController,
    private loadingCtrl: LoadingController,
    private sqliteService: SqliteServiceProvider,
    private cameraService: CameraServiceProvider
  ) {
  }

  /**打开相册 */
  openAlbum() {
    var options = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      saveToPhotoAlbum: false,
      correctOrientation: true
    };
    this.getImage(options);
  }

  /**打开相机 */
  openCamera() {
    var options = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      sourceType: this.camera.PictureSourceType.CAMERA,
      saveToPhotoAlbum: false,
      correctOrientation: true
    };
    this.getImage(options);
  }

  clickImage(item: any) {
    this.photoViewer.show(item, '图片预览');
  }

  getImage(options) {
    this.cameraService.openCamera(options).then((imagePath) => {
      this.uploadImage(imagePath);
    }, (err) => {
      this.presentToast('Error while selecting image.');
    });
  }

  // 上传图像
  public uploadImage(newFileName: any) {
    let url: string = MyApp.getCurrentUrl() + "/system/api/tubescanning.svc/SaveImage";
    var targetPath = this.pathForImage(newFileName);
    var options = {
      fileKey: "imgfile",
      fileName: newFileName,
      httpMethod: 'POST',
      mimeType: "image/jpeg'",
      params: {}
    };
    const fileTransfer: FileTransferObject = this.transfer.create();
    this.loading = this.loadingCtrl.create({
      content: '正在上传...',
      cssClass: 'loadingwrapper'
    });
    this.loading.present();
    // 使用文件传输上传图像
    fileTransfer.upload(targetPath, url, options).then(data => {
      this.loading.dismissAll()
      alert(JSON.stringify(data));
      this.presentToast('图像上传成功.');
    }, err => {
      this.loading.dismissAll()
      this.presentToast('图像上传失败.');
    });
  }

  //为图像创建新名称
  private createFileName() {
    var d = new Date(),
      n = d.getTime(),
      newFileName = n + ".jpg";
    return newFileName;
  }

  private presentToast(text) {
    let toast = this.toastCtrl.create({
      message: text,
      duration: 3000,
      position: 'top'
    });
    toast.present();
  }
}

3. 后端

[OperationContract]
        [WebInvoke(UriTemplate = "SaveImage", Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
        public string SaveImage()
        {
            try
            {
                HttpPostedFile file = HttpContext.Current.Request.Files["imgfile"];
                if (file == null)
                    return null;
                string targetFilePath = AppDomain.CurrentDomain.BaseDirectory + file.FileName;
                file.SaveAs(targetFilePath);
                return file.FileName.ToString();
            }
            catch (Exception e)
            {
                return e.Message.ToString();
            }
        }

到这里遇到一个问题上传图片会遇到 在调用 HttpRequest.GetBufferlessinputStream 之后,此方法或属性不受支持错误,百度老半天查不到问题所在,实在没办法用了Google最后发现需要使用Module在WCF根目录下创建WcfReadEntityBodyModeWorkaroundModule.cs类该类继承IHttpModule

3.1 这是解决办法地址

https://blogs.msdn.microsoft.com/praburaj/2012/09/13/httpcontext-current-request-inputstream-property-throws-exception-this-method-or-property-is-not-supported-after-httprequest-getbufferlessinputstream-has-been-invoked-or-httpcontext-cur/

3.2 接下来直接上代码

public class WcfReadEntityBodyModeWorkaroundModule : IHttpModule
    {
        public void Dispose()
        {
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += context_BeginRequest;
        }
        void context_BeginRequest(object sender, EventArgs e)
        {
            //This will force the HttpContext.Request.ReadEntityBody to be "Classic" and will ensure compatibility..
            Stream stream = (sender as HttpApplication).Request.InputStream;
        }
    }

3.3 Web.config 也需要加入如下配置

 <appSettings> 
     <add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
  </appSettings>

到这里算是解决了上述问题这时候可以上传小文件在上传大文件的时候还是会报错。这是因为上传有限制大小在Web.config的system.serviceModel加入如下配置

<bindings>
      <webHttpBinding>
        <binding maxBufferPoolSize="5242880000" maxBufferSize="655360000" maxReceivedMessageSize="655360000">
          <security mode="None"/>
        </binding>
      </webHttpBinding>
    </bindings>

需要注意的是需要和服务.svc进行绑定如图:


QQ截图20181204094916.jpg

OK到此大功告成。结束!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • 工作的交接 交接工作时交接双方清楚明确,双方确认。
    93650345d0d1阅读 194评论 0 0
  • 第一次遇见你 我就深深的喜欢上你 可是你却不知道 我是谁 我就是 心里兵荒马乱 而你不知情的人 我就是 已经想好余...
    郁鹏阅读 191评论 0 1
  • 岁月的年轮 刻下了 一圈又一圈的印痕 多少个日夜 我想放弃 但心中的意念 督促我不断前行 我因你写诗文 想留住曾经...
    六月天气阅读 415评论 48 76
  • 文/梁爽 理性天蝎女 治拎不清、玻璃心,忌用力过猛 点赞你挑剔的心 前几天,我升职了。 事后人事部好友告诉我,在选...
    哪梁爽哪呆着阅读 504评论 1 10