前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【技巧】ionic3视频上传

【技巧】ionic3视频上传

作者头像
IT晴天
发布2018-08-20 10:21:02
6910
发布2018-08-20 10:21:02
举报
文章被收录于专栏:ionic3+ionic3+

本文前提认为读者有基本的angular2基础,知道怎么import,知道provider怎么用

有人问到视频上传这个问题,那我还是写一下吧,其实基本参考《ionic3多文件上传》这文章也行,不过对于单文件上传就不用那么复杂了,步骤如下:

1、写一个上传文件的后台服务

一般开发到这个功能,那上传后台服务一般都提供了的,视乎后台服务技术不同,这部分我就不详解也不提供实例代码了。

2、弄一个上传测试页面验证上述服务是否可用

复制下面代码保存为一个html文件,作为上传测试页面。

代码语言:javascript
复制
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="http://localhost:8080/uploadFile" method="POST" enctype="multipart/form-data">
    <p>单文件上传:</><br/>
    <input type="file" name="file"/>
    <input type="submit" value = "上传"/>
</form>
<form method="POST" enctype="multipart/form-data" 
    action="http://localhost:8080/uploadFiles">
    <p>多文件上传:</>
    <p>文件1:<input type="file" name="file" /></p>
    <p>文件2:<input type="file" name="file" /></p>
    <p><input type="submit" value="上传" /></p>
</form>
<a href="http://localhost:8080/testDownload">下载</a>
</body>
</html>

注意<input type="file" name="file"/>这段的name的值和后台上传服务的参数一致

浏览器打开这页面,选择文件上传,在后台服务的文件存放位置看看是否接收到文件,如收到表示后台服务可用。

image.png

3、安装相应的Cordova插件

1)这里使用fileTransfer上传方式,所以安装fileTransfer插件及相应的ionic-native模块:

ionic cordova plugin add cordova-plugin-file-transfer npm install @ionic-native/transfer --save

2)这里使用camera插件获取视频,所以安装该插件及相应的ionic-native模块:

ionic cordova plugin add cordova-plugin-camera npm install @ionic-native/camera --save

插件安装完,记得在app.module.ts中的providers里添加:

代码语言:javascript
复制
providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Transfer,
    Camera
  ]

4、创建一个封装操作的provider文件

创建一个FileProvider.ts文件(因为camera插件用的是Callback方式,而fileTransfer用了Promise,所以这里贪方便沿用,可以统一为同一种方式。):

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { AlertController, Loading, LoadingController, ActionSheetController } from 'ionic-angular';
import { Transfer, FileUploadOptions, TransferObject } from '@ionic-native/transfer';
import { Camera, CameraOptions } from '@ionic-native/camera';

/*
  Generated class for the FileProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class FileProvider {

  fileTransfer: TransferObject = this.transfer.create();
  loading: Loading;
  constructor(private transfer: Transfer, private alertCtrl:AlertController, 
  private loadingCtrl: LoadingController, private camera: Camera,
  private actionSheetCtrl: ActionSheetController) {
    
  }
  
  /**
   * 上传文件
   * @param fileUrl 文件路径
   * @param url 服务器地址
   * @param options 选项
   */
  public uploadByTransfer(fileUrl: string, url: string, options?: FileUploadOptions){
    if(!options){
      options = {
        fileKey: 'file',
        fileName: fileUrl.substr(fileUrl.lastIndexOf('/')+1)
      };
    }
   return this.fileTransfer.upload(fileUrl, url, options);
  }

  /**
   * 显示拍照选择
   */
  choosePhoto(successCallback, errorCallback, options?: CameraOptions) {
    if(!options){
      options = {
          destinationType: this.camera.DestinationType.FILE_URI,
          sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
          encodingType: this.camera.EncodingType.JPEG,
          saveToPhotoAlbum: true,
          mediaType: 1,   //0为图片,1为视频
          targetWidth: 400,
          targetHeight: 400
      };
    }
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择图片来源',
      buttons: [
        {
          text: '相册',
          role: 'destructive',
          handler: () => {
            options.sourceType = this.camera.PictureSourceType.PHOTOLIBRARY;
            this.getLocalImage(successCallback, errorCallback, options);
          }
        },
        {
          text: '拍照',
          handler: () => {
            options.sourceType = this.camera.PictureSourceType.CAMERA
            this.getLocalImage(successCallback, errorCallback, options);
          }
        },
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            
          }
        }
      ]
    });
    actionSheet.present();
  }

    /**
   * Default is CAMERA. PHOTOLIBRARY : 0, CAMERA : 1, SAVEDPHOTOALBUM : 2
   */
  getLocalImage(successCallback, errorCallback, options: CameraOptions){
    this.camera.getPicture(options).then(imageData => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64:
      // let base64Image = 'data:image/jpeg;base64,' + imageData;
      successCallback(imageData);
    }, err => {
      // Handle error
      errorCallback(err);
    });
  }
}

关于camera插件参数看github文档,其中特别注意mediaType的值,1为视频

5、在ionic3代码里调用:

html添加一个按钮:

代码语言:javascript
复制
<button ion-button (click)="onTest()">upload</button>

ts里补充按钮事件:

代码语言:javascript
复制
 onTest(){
    this.fileProvider.choosePhoto(res=>{
      this.fileProvider.uploadByTransfer(res, 'http://后台上传服务')
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.log(err);
      });
    },err=>{
      console.log(err);
    });
  }

6、最后在真机调试!真机调试!连wifi!

成功效果如图:

image.png

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.08.29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、写一个上传文件的后台服务
  • 2、弄一个上传测试页面验证上述服务是否可用
  • 3、安装相应的Cordova插件
  • 4、创建一个封装操作的provider文件
  • 5、在ionic3代码里调用:
  • 6、最后在真机调试!真机调试!连wifi!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档