2015-11-19 29 views
13

Vấn đề của tôi như sau.Tải tệp lên trong ứng dụng Ionic bằng API Web

Tôi đã cung cấp API WEB nơi tôi phải thêm ảnh bảng.

Tôi phải làm gì?

  • tài nên có thể chọn hình ảnh từ điện thoại
  • Người dùng có thể thêm Tên của ban
  • Khi người dùng nhấp chuột vào gửi, ký tên bảng và hình ảnh ban nên đăng sử dụng Web API với phương pháp PUT. Dưới đây dưới đây là WEB API Chi tiết

WEB API Chi tiết

Tiêu đề

liệu

  • board_id: 321
  • board_title: | Tiêu đề |
  • board_background: | Tệp |

Tôi đã sử dụng cordovaImagePicker plugin để chọn hình ảnh và sau đó tôi gặp khó khăn khi tải nó lên Máy chủ.

Tôi có thể sử dụng plugin chuyển tập tin cordova nhưng tôi nghĩ điều đó sẽ không giúp tôi trong trường hợp này vì không có nơi được chỉ định để lưu trữ hình ảnh. Tất cả các quản lý tập tin được thực hiện bởi WEB API, chúng tôi phải chỉ gửi tập tin với dữ liệu.

Trả lời

7

Sau khi thử một giải pháp rất nhiều, tôi đã đi kèm với câu trả lời dưới đây.

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> 

chỉ

.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]); 
         }); 
        }); 
       } 
      }; 
     }]) 

khiển

.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." 
        }); 
       }); 
      } 
     }) 

Dịch vụ

.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 
      }; 
     }) 

Sau khi triển khai ứng dụng để chọn tệp android/iPhone sẽ xử lý hình ảnh duyệt dựa trên hệ điều hành.

+0

bạn có thể chia sẻ ứng dụng demo nhỏ cho ví dụ này không, – Sutirth

3

Một điều đơn giản tôi có thể đề xuất,

Sử dụng thẻ đầu vào ["tệp"] để chọn hình ảnh. Bạn sẽ nhận được đối tượng tệp và url tạm thời. với url này, bạn có thể hiển thị hình ảnh trong biểu mẫu.

Sau đó, sử dụng biểu mẫu Dữ liệu để nối hình ảnh và trường khác.

ví dụ:

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); 

Hy vọng nó sẽ giúp bạn và đáp ứng các yêu cầu của bạn.

3

Trước hết cần phải chọn hình ảnh từ thiết bị.

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); 
      } 
     }; 

Bạn có thể thay đổi loại nguồn để nhập nếu cần.

Khi thành công, bạn sẽ trực tiếp sử dụng hoặc chuyển đổi nó thành base64 như được đề cập bên dưới để tải lên.

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

Sau này, bạn có thể sử dụng FileTransfer plugin để tải lên tệp và theo dõi tiến trình cùng một lúc.

cordovaFileTransfer.upload() 
       .then(function (result) {}, 
        function (err) {}, 
        function (progress) {}); 
Các vấn đề liên quan