使用angular / angularjs将文件上传到firebase

时间:2017-03-23 10:13:34

标签: angularjs firebase angularfire firebase-storage

我正在使用以下内容通过angular / angularfire在我的firebase存储上传图像:

<form ng-submit="uploadFile(file)">
  <input type="file" accept="txt" file-model="file" class="form-control">
  <button type="submit" class="btn btn-primary">Upload File</button>
</form>

和js:

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

app.controller('myController', ['$scope', '$firebaseStorage', function($scope,     $firebaseStorage) {

 // Create a Firebase Storage reference
 var storage = firebase.storage();
 var storageRef = storage.ref();
 var filesRef = storageRef.child('files');

 $scope.uploadFile = function(file) {
console.log("Let's upload a file!");
console.log($scope.file);
var storageRef = firebase.storage().ref("files");
// var storageRef = firebase.storage().ref("files");
$firebaseStorage(filesRef).$put($scope.file);
};

 }]);

问题是,如果我之后上传了另一张图片,它将取代之前上传的图像(我想这是因为文件名被视为'文件',因此自动替换它)

有没有办法避免这种情况?例如,要上传带有文件名的图像吗?

道路应该如何?

非常感谢你的帮助

1 个答案:

答案 0 :(得分:1)

   app.controller('myController', ['$scope','$firebaseStorage',function($scope,     $firebaseStorage) {

 // Create a Firebase Storage reference
 var storage = firebase.storage();
 var storageRef = storage.ref();
 var filesRef = storageRef.child('files');

 $scope.uploadFile = function(file) {
console.log("Let's upload a file!");
console.log($scope.file);
storageRef.child(file.name).put(file);
    storageRef.on('state_changed', function(snapshot) {
                var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;

            }, function() {
                //handle error
            }, function() {
           //url of storage file 
                var downloadURL = storageRef.snapshot.downloadURL;
                console.log(downloadURL)
                //you will get url of snapshot
            });
     };

 }]);

你可以使用文件名或时间戳.so每次它都是唯一的。

<form ng-submit="uploadFile(file)">
  <input type="file" accept="txt" file-model="file" class="form-control">
  <button type="submit" class="btn btn-primary">Upload File</button>
</form>

如果您遇到任何问题,请告诉我