Не могу получить firebase, чтобы перестать переопределять старые картинки, когда я загружаю их в javascript / jquery - PullRequest
0 голосов
/ 05 апреля 2019

Firebase перезаписывает мои старые фотографии каждый раз, когда я загружаю новую фотографию, я хочу, чтобы она сохраняла мои старые фотографии

<!DOCTYPE html>
<html>
<head>
  <title>Firebase Storage</title>  
</head>
<body>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
  <input type='file' id="imgInp" />
  <img id="blah" src="#" alt="your image" />
<button type="submit" onclick="window.open('#blah')">Download!</button>

    </form>    

    <a download="new-image.png" id="download">Download</a>







<label>Image File:</label>
<br/>

    <button onclick="myFunction()">Click me</button>
    <button onclick="myFunctiondown()">Click me</button>
    <button onclick="myFunctionleft()">Click me</button>
    <button onclick="myFunctionleft2()">Click me</button>
    <button onclick="myFunctiontext()">Click me</button>


    <input type="file" id="imageLoader" name="imageLoader" />

<h1>Example of using <code>&lt;canvas&gt;</code></h1>

<p>This example shows how a photo is loaded in a <code>&lt;canvas&gt;</code> tag and then flipped.</p>

<p>Click on the photo to flip (provided, of course, that your browser supports <code>&lt;canvas&gt;</code>)</p>

<canvas id="canvas" style="border:1px red solid;"></canvas>

<a download="new-image.png" id="download">Download</a>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>    

 <script src="add-download-btn.js"></script>   

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

  <script src="https://www.gstatic.com/firebasejs/5.8.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/5.8.0/firebase-storage.js"></script>

  <h1>Firebase Storage</h1>  

  <input type="file" id="fileButton">

  <div id="image" style=""></div>


<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>

    <style>

        img {


            height: 200px;
            width: 200px;
        }









    #image{
    height:250px;
    width:250px;
    float:left;
}


        #dwnld{
    float:left;
}

.button {
    appearance: button;
    -moz-appearance: button;
    -webkit-appearance: button;
    text-decoration: none; font: menu; color: ButtonText;
    display: inline-block; padding: 2px 8px;
    font-size: 15px;
}    




    .btn {

  padding: 5px 10px;

  font-size: 16px;

  border-radius: 3px;

  border: solid 1px #C0392B;

  background-color: #E74C3C;

  text-decoration: none;

  color: white;

}



.btn:hover {

  opacity: .9;

}



.btn:active {

  opacity: 1;

}



             canvas {
    height: 50vh;    

    }  



    </style>

    <script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyAMEuYur7_ExqF92Os02kRlZbSXIHdfDjE",
    authDomain: "danniauth.firebaseapp.com",
    databaseURL: "https://danniauth.firebaseio.com",

    projectId: "danniauth",
    storageBucket: "danniauth.appspot.com",
    messagingSenderId: "279422179745"
  };
  firebase.initializeApp(config);
</script>

  <script>

//$(document).ready(function () {
  //          $("#blah").click(function () {
//                $("img").animate({

  //                  height: '+=5px',
//                    width: '+=5px'
  //              });

//            var button = document.getElementById('download');
//  button.setAttribute( 'href', can.toDataURL('image/png', 1) );



//            });
    //    });




   var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);


var can = document.getElementById('canvas');
var ctx = can.getContext('2d');




var img = new Image();


function handleImage(e) {
  var reader = new FileReader();
  reader.onload = function(event) {

    img.onload = function() {
      can.width = img.width;
      can.height = img.height;
      ctx.drawImage(img, 0, 0, img.width, img.height);
      ctx.save();
    }
    img.src = event.target.result;
  }
  reader.readAsDataURL(e.target.files[0]);
}




function myFunction() {
  console.log('here');
   can.width = img.width;
      can.height = img.height;

    ctx.translate(img.width - 500, img.height - 505);
  ctx.rotate(Math.PI/2);
  ctx.translate(-(img.width - 500), -(img.height - 505));
    ctx.drawImage(img, 60, 60, img.width, img.height);

  var button = document.getElementById('download');
  button.setAttribute( 'href', can.toDataURL('image/png', 1) );

};    



function myFunctiondown() {
  console.log('here');
   can.width = img.width;
      can.height = img.height;

    ctx.translate(img.width - 1, img.height - 1);
  ctx.rotate(Math.PI);
//  ctx.translate(-(img.width - 500), -(img.height - 505));
    ctx.drawImage(img, 0, 0, img.width, img.height);

  var button = document.getElementById('download');
  button.setAttribute( 'href', can.toDataURL('image/png', 1) );

};        



function myFunctionleft() {
  console.log('here');
   can.width = img.width;
      can.height = img.height;

    ctx.translate(img.width - 500, img.height - 500);
  ctx.rotate(Math.PI/360);
  ctx.translate(-(img.width - 500), -(img.height - 505));
    ctx.drawImage(img, 0, 0, img.width, img.height);

  var button = document.getElementById('download');
  button.setAttribute( 'href', can.toDataURL('image/png', 1) );

};    




        function myFunctionleft2() {
  console.log('here');
   can.width = img.width;
      can.height = img.height;

    ctx.translate(img.width - 500, img.height - 500);
  ctx.rotate(270 * Math.PI / 180);
  ctx.translate(-(img.width - 500), -(img.height - 505));
    ctx.drawImage(img, 164, 164, img.width, img.height);

  var button = document.getElementById('download');
  button.setAttribute( 'href', can.toDataURL('image/png', 1) );

};        












//////////////////////////////      




  //    function readURL(input) {

//  if (input.files && input.files[0]) {
//    var reader = new FileReader();

//    reader.onload = function(e) {
//      $('#blah').attr('src', e.target.result);
 //   }

 //   reader.readAsDataURL(input.files[0]);
//  }
//}

//$("#imgInp").change(function() {
//  readURL(this);
//});     


//$('#download').attr('scr', e.target.result())       








    /*
     *
     * Create a variable to reference the upload button.
     *
     */
    var fileButton = $('#fileButton' );

    /*
     *
     * Add a change event listener the upload button. 
     *
     */
    fileButton.change(function(event){

      //      ImageTools.resize(this.files[0], {
    //    width: 320, // maximum width
  //      height: 240 // maximum height
//    }, function(blob, didItResize) {
        // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
   //     document.getElementById('image').src = window.URL.createObjectURL(blob);
        // you can also now upload this blob using an XHR.
 //   });


      /*
       * Create a variable and get the relevant file objec
       */





        var file = event.target.files[0];

      /* 
       * Create a Firebase reference for a new image.
                                       *user/number.jpg
       */  //+ new Date().getTime() + file.name).put(file);

      var ref = firebase.storage().ref('/images/testing.jpg');
      var user = firebase.auth().currentUser;
      var storageRef = firebase.storage().ref("user");
      var userRef = storageRef.child(user.uid);    


        firebase.auth().onAuthStateChanged(function(user) {
        if( user )
        {
          $('.unauthed').hide();
          $('.authed').show();
            console.log(user.uid);
        }
        else
        {

        }
      });

      /*
       * Upload the file using the Firebase reference. 
       */
        userRef.put(file);
        ref.put(file);

      /*
       * Retrieve the full URL of the uploaded file and place it into an IMG tag 
       * in the DIV with the id of IMAGE.
       *$('#image').width(100);
       */

          ref.getDownloadURL().then(function(url){

          $('#image').html('<img src="'+url+'">');

      });      

    });

  </script>

</body>
</html>

1 Ответ

0 голосов
/ 05 апреля 2019

В настоящее время вы загружаете файлы с:

userRef.put(file);
ref.put(file);

Каждый раз, когда вы запускаете этот код, он добавляет данные в одно и то же место, перезаписывая все, что вы ранее написали в этом месте.

Чтобы сохранить несколько файлов, вам нужно будет создавать новый уникальный StorageReference каждый раз, когда вы хотите загрузить файл.Простой способ сделать это - использовать метку времени в имени файла:

userRef.child(Date.now()).put(file);

Это означает, что каждый файл хранится в «папке» для пользователя, а затем с текущей меткой времени под ним..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...