【问题标题】:Uploading files in Ionic application using Web API使用 Web API 在 Ionic 应用程序中上传文件
【发布时间】:2016-02-21 09:45:42
【问题描述】:

我的问题如下。

我已经提供了 WEB API,我必须在其中添加板图片。

我必须做什么?

  • 用户应该能够从手机中选择图片
  • 用户可以添加板子名称
  • 当用户点击提交时,输入的版块名称和版块图片应使用 Web API 和 PUT 方法发布。以下是 WEB API 详细信息

WEB API 详情

标题

数据

  • board_id:321
  • board_title: |标题 |
  • board_background:|文件 |

我使用 cordovaImagePicker 插件来选择图像,然后我卡住了将其上传到服务器。

我可以使用 cordova 文件传输插件,但我认为在这种情况下这对我没有帮助,因为没有指定的存储图像的位置。 WEB API 完成的所有文件管理,我们只需要使用数据发布文件。

【问题讨论】:

    标签: angularjs ionic-framework ionic asp.net-web-api2


    【解决方案1】:

    在尝试了很多解决方案后,我得到了以下答案。

    Board.html

        <ion-view>
            <ion-nav-bar class="bar">
                <ion-nav-title>
                    <h1 class="title">
                        Create Board
                    </h1>
                </ion-nav-title>
            </ion-nav-bar>
            <form name="boardForm" ng-submit="addBoard(data)">
                <ion-content padding="false" scroll="true" has-bouncing="false">
                    <div id="form">
                        <div style="text-align: center; padding-top: 2%; padding-bottom: 2%;">
                            <div id="image-preview">
                                <label for="image-upload" id="image-label"><img src="{{ImagePrefix}}/task_plus.png" alt=""/></label>
                                <input type="file" name="board_background" id="image-upload" file-model="data.board_background">
                            </div>
                            <p>Add Cover</p>
                        </div>
                        <ion-list>
                            <ion-item style="background-color: #F8F8F8;">
                                <label class="control-label" for="board_name">BOARD NAME</label>
                            </ion-item>
                            <ion-item ng-class="{true:'error'}[submitted && boardForm.board_title.$invalid]">
                                <input type="text" id="board_name" ng-model="data.board_title"
                                       placeholder="Add a Name" name="board_title" required>
    
                                <p ng-show="submitted && boardForm.board_title.$error.required">
                                    Please enter a board name
                                </p>
                            </ion-item>
                        </ion-list>
                    </div>
                </ion-content>
                <ion-footer-bar>
                    <button class="button button-block control-button bottomOfPage"
                            ng-click="submitted = true">
                        CREATE
                    </button>
                </ion-footer-bar>
            </form>
        </ion-view>
    

    指令

        .directive('fileModel', ['$parse', function ($parse) {
                return {
                    restrict: 'A',
                    link: function (scope, element, attrs) {
                        var model = $parse(attrs.fileModel);
                        var modelSetter = model.assign;
    
                        element.bind('change', function () {
                            scope.$apply(function () {
                                modelSetter(scope, element[0].files[0]);
                            });
                        });
                    }
                };
            }])
    

    控制器

        .controller('ManageBoardCtrl', function ($scope, $http, $ionicPopup, $state, BoardService) {
                $scope.submitted = false;
                $scope.data = {};
                $scope.addBoard = function(formData) {
                    BoardService.CreateBoard(formData).then(function(response) {
                        if (response === "success") {
                            $ionicPopup.alert({
                                title: "Success",
                                template: "Board created successfully"
                            });
                        }
                    }, function (response) {
                        $ionicPopup.alert({
                            title: "Failed",
                            template: "Somethings wrong, Can not create boards at now."
                        });
                    });
                }
            })
    

    服务

        .service('BoardService', function ($q, $http) {
                var getUrl = API_URL + "boards";
    
                var createBoard = function (fData) {
                    var formData = new FormData();
                    formData.append("board_title", fData.board_title);
                    formData.append("board_background", fData.board_background);
    
                    return $q(function (resolve, reject) {
                        $http({
                            transformRequest: angular.identity,
                            method: 'POST',
                            url: getUrl,
                            headers: { 'Content-Type': undefined },
                            data: formData
                        }).success(function (response) {
                            if (response.success === true) {
                                resolve('success');
                            } else {
                                reject('fail');
                            }
                        }).error(function () {
                            reject('requesterror');
                        });
                    });
                };
    
                return {
                    CreateBoard: createBoard
                };
            })
    

    在为安卓/iPhone文件选择部署应用程序后,将处理基于操作系统的浏览图像。

    【讨论】:

    • 你能分享一下这个例子的小演示应用吗,
    【解决方案2】:

    我可以建议一件简单的事情,

    使用 input["file"] 标签来选择图片。您将获得文件对象和一个临时 url。使用此 url,您可以在表单中显示图像。

    然后使用 formData 附加图像和其他字段。

    例如

     var fd = new FormData();
     fd.append('board_background', $scope.image, $scope.image.name);
     fd.append('board_id', 321);
     fd.append('board_title', 'Dummy title');
    
     var xhr = new XMLHttpRequest();
     xhr.open('PUT', YOUR_URL, true);
    
     xhr.onload(function(res){
        // Write your callback here.
     });
    
     // Send the Data.
     xhr.send(fd);
    

    希望它能帮助您并满足您的要求。

    【讨论】:

      【解决方案3】:

      首先需要从设备中选择图片。

      vm.getImages = function () {
                  var options = {
                      quality: 70,
                      destinationType: Camera.DestinationType.DATA_URL,
                      sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                      allowEdit: true,
                      correctOrientation:true,
                      encodingType: Camera.EncodingType.JPEG,
                      targetWidth: 300,
                      popoverOptions: CameraPopoverOptions,
                      saveToPhotoAlbum: true
                  };
      
                  navigator.camera.getPicture(onSuccess, onFail, options);
      
                  function onSuccess(imageURI) {                
                      vm.image = "data:image/jpeg;base64," + imageURI;
                      vm.imageURI = imageURI;
                  }
      
                  function onFail(message) {                
                      console.log('Failed because: ' + message);
                  }
              };
      

      如果需要,您可以更改输入的源类型。

      sourceType: Camera.PictureSourceType.CAMERA,
      

      成功后,您可以直接使用 ImageURI 或将其转换为 base64,如下所述进行上传。

      vm.image = "data:image/jpeg;base64," + imageURI;
      

      之后,您可以使用FileTransfer plugin 上传文件并同时跟踪进度。

      cordovaFileTransfer.upload()
                      .then(function (result) {},
                        function (err) {},
                        function (progress) {});
      

      【讨论】:

        【解决方案4】:

        下面的链接一定会对你有所帮助:

        http://ionicmobile.blogspot.in/2015/10/jquery-file-upload.html

        根据需要进行适当的更改。任何帮助让我知道...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-22
          • 2018-08-16
          • 2016-10-15
          • 1970-01-01
          • 1970-01-01
          • 2013-11-05
          • 1970-01-01
          相关资源
          最近更新 更多