萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

AngularJS 應用訪問 Android 手機圖片庫:基於 myMoKit REST API 實戰

項目背景

Android/iOS 缺乏統一的遠程訪問手機媒體庫 API。myMoKit 提供 REST 服務,暴露手機圖片、視頻等資源,前端可通過 AngularJS 輕鬆調用。

服務端 API 結構

啟動 myMoKit 服務後,通過 Web URL 可查看所有暴露的 REST 端點,例如:

  • /services/api/media/image — 獲取圖片列表
  • /services/api/media/video — 獲取視頻列表
  • /services/stream?uri=...&id=...&kind=1 — 串流媒體內容

AngularJS 服務封裝

angular.module('resources.media', ['ngResource']);
angular.module('resources.media').factory('Media', [
  '$rootScope', '$resource', '$location', '$http',
  function($rootScope, $resource, $location, $http) {
    var mediaServices = {};
    mediaServices.getAllMedia = function(mediaType) {
      var path = $rootScope.host + '/services/api/media/' + mediaType;
      return $resource(path, {}, {
        get: { method: 'GET', isArray: false }
      });
    };
    return mediaServices;
  }
]);

控制器調用並綁定視圖

var getAllImages = function() {
  Media.getAllMedia('image').get().$promise.then(
    function success(resp) {
      $scope.allImages = resp;
      $scope.images = $scope.allImages.images;
    },
    function err(httpResponse) {
      $scope.errorMsg = httpResponse.status;
    }
  );
};

var getAllVideos = function() {
  Media.getAllMedia('video').get().$promise.then(
    function success(resp) {
      $scope.allVideos = resp;
      $scope.videos = $scope.allVideos.videos;
    },
    function err(httpResponse) {
      $scope.errorMsg = httpResponse.status;
    }
  );
};

HTML 模板展示圖片牆

<div class="alert alert-info">
  <h4 class="alert-heading">Image Gallery</h4>
  <ul class="row">
    <li class="col-lg-2 col-md-2 col-sm-3 col-xs-4" 
        ng-repeat="image in images" style="margin-bottom:25px">
      <img class="img-responsive" 
           ng-click="showImage($index)" 
           ng-src="{{streamImageLink}}?uri={{image.contentUri}}&&id={{image.id}}&kind=1" />
    </li>
  </ul>
</div>

關鍵點總結

  • 使用 $resource 封裝 REST API,自帶 Promise 支援。
  • 圖片/視頻通過串流端點動態加載,無需下載完整文件。
  • 響應式佈局配合 Bootstrap 類名,適配多種屏幕尺寸。
copyright © 萬盛學電腦網 all rights reserved