首 页  -  技术分享  - ionic图片上传

ionic图片上传

分享者:张香君     2015-12-09

1.首先下载这个插件:

可以在package.json文件中添加“cordova-plugin-device"来添加,也可以直接在ngCordova官网里找到相应的命令来下载,

命令为:

cordova plugin add cordova-plugin-camera

2.在ionic项目中要使用这个插件的页面相应的控制器里添加相应的插件名来引用,记得在依赖项里要加ngCordova,不然会出错。

3.在控制器里写入相应的js代码(这些代码在ngCordova官网插件的应用上有详细的方法调用,根据具体的需要来写自己所需要的功能的代码)我这个代码是来实现页面上要显示7张从手机相册中选择的图片,

js代码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
$scope.takePicture = function (img) {
    var options = {
        quality: 75,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        targetWidth: 500,
        targetHeight: 500,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false
};
 
    $cordovaCamera.getPicture(options).then(function (imageData) {
            // alert(imageData);
if (img == 1) {
                $scope.data.IDCardImage1 = imageData;
                $scope.imgURI1 = "data:image/jpeg;base64," + imageData;
            }
            if (img == 2) {
                $scope.data.IDCardImage2 = imageData;
                $scope.imgURI2 = "data:image/jpeg;base64," + imageData;
            }
            if (img == 3) {
                $scope.data.Qualified = imageData;
                $scope.imgURI3 = "data:image/jpeg;base64," + imageData;
            }
            if (img == 4) {
                $scope.data.CredentialImage = imageData;
                $scope.imgURI4 = "data:image/jpeg;base64," + imageData;
            }
            if (img == 5) {
                $scope.data.CarInfoImage1 = imageData;
                $scope.imgURI5 = "data:image/jpeg;base64," + imageData;
            }
            if (img == 6) {
                $scope.data.CarInfoImage2 = imageData;
                $scope.imgURI6 = "data:image/jpeg;base64," + imageData;
            }
            if (img == 7) {
                $scope.data.CarInfoImage3 = imageData;
                $scope.imgURI7 = "data:image/jpeg;base64," + imageData;
            } else {
                return "";
            }
        }
    );
};
$scope.take = function () {
    this.takePicture();
}

  

4.html页面的代码如下(其中ng-src中要把图片转化为base64格式,上传到服务器)我这里只贴出了显示两张图片的代码,其他的类似:

 

1
2
3
4
5
6
7
8
9
10
11
<div class="row">
    <div class="col padding" ng-click="takePicture(1)">
        <img ng-src="data:image/jpeg;base64,{{data.IDCardImage1}}"
style="border: 1px dashed gray;width: 100px;height: 100px;background-color: #f0f0f0"/>
    </div>
    <div class="col padding" ng-click="takePicture(2)">
        <img ng-src="data:image/jpeg;base64,{{data.IDCardImage2}}"
style="border: 1px dashed gray;width: 100px;height: 100px;background-color: #f0f0f0"/>
    </div>
    <div class="col padding"></div>
</div>