角度输入上传 - 获取文件名并上传

时间:2016-02-15 06:01:17

标签: javascript angularjs file-upload input upload

我正在尝试为Ionic / Angular应用程序的用户配置文件更新部分创建图像上传功能。上传功能是表单的一部分,我无法检索图像和文件名。我怎么能得到这两个项目?以下是我的代码:

表格(查看):

<div class="item-input"> 
 <!--list item-->  
 <div data-ng-repeat="user in users"> 

    Username: <input type="text" placeholder="Enter the event name" name="username" ng-model="user.username" required> 

    Password: <input type="password" placeholder="Enter the password" name="password" ng-model="user.password" required> 

    Email: <input type="text" placeholder="Enter the email" name="email" ng-model="user.email" required> 

    Hometown: <input type="text" placeholder="Enter your hometown" name="hometown" ng-model="user.hometown" required> 

    Firstname: <input type="text" name="firstname" ng-model="user.firstname" required> 

    Lastname: <input type="text" name="lastname" ng-model="user.lastname" required>

    Birthday: <date-picker ng-model="user.birthday"></date-picker>

    Image:  <input type="file" name="file" ng-model="filename"> 
        <button ng-click="upload(file)">Upload</button>   

    <button class="button button-block button-positive" ng-click="editprofile(user)">
     Edit Account
    </button>

    <button class="button button-block button-positive" ng-click="deleteprofile()">
     Delete Account
    </button>

 </div>

控制器

.controller('ProfileUpdateCtrl', function($http, $state, $http, $cordovaOauth, $stateParams, $rootScope, $scope, UserFac) {  
   //removed the working features to focus on the uploading part. 
   $scope.upload = function(file) {  
      var filename = $scope.file.name; 
      //need to know how to get the data of the image and save as formdata
   }
 }); 

2 个答案:

答案 0 :(得分:2)

我使用angularjs创建了一个图像上传示例。它检索图像及其文件名。我希望它可以帮助你。

HTML:

 <div ng-app="test">
    <div ng-controller="UploadCtrl">
     Image:
     <input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" />
     <img ng-src="{{ thumbnail.dataUrl }}" /> <!--Display the image -->
 </div>

控制器:

angular.module('test', []);
angular.module('test') .controller('UploadCtrl', function($scope, $timeout) {

// Read the image using the file reader 
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function(files) {
  if (files != null) {
    var file = files[0];
     if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
      $timeout(function() {
        var fileReader = new FileReader();
        fileReader.readAsDataURL(file); // convert the image to data url. 
        fileReader.onload = function(e) {
          $timeout(function() {
            $scope.thumbnail.dataUrl = e.target.result; // Retrieve the image. 
          });
        }
      });
    }
  }
};
});

JS小提琴:https://jsfiddle.net/um8p6pd7/2/

祝你好运!

答案 1 :(得分:0)

您需要使用$ cordovaFileTransfer将文件上传到服务器。 安装$ cordovaFileTransfer插件,然后您就可以将文件上传到服务器,在服务器端,您需要创建获取文件的路径并将其保存到文件夹中。