简体   繁体   中英

Upload file to firebase with angular / angularjs

I'm using the following to upload images on my firebase storage via angular / angularfire:

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

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

 }]);

The problem is if I upload another image after, it will replace the previous one uploaded ( I suppose it's due to the fact the file name is being taken as 'files', and so replace it automatically)

Is there a way to avoid this? For example, to upload the image with the name of the file instead?

How the path should be?

Thanks a lot for your help

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

 }]);

you can use filename or timestamp .so everytime it will be unique.

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

let me know if you have any problem facing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM