2017-08-05 127 views
0

我設法使用HTML和JS在我的頁面上加載圖像,但我似乎無法將圖像發佈到我的MongoDB,並且它不會顯示在我的家中'頁面。使用HTML,JS和MONGODB上傳和顯示圖像

HTML:

<div class="container"> 
    <h1 style="text-align: center">Post a New Guitar</h1> 
    <div class="col-md-6"> 
     <form action="/guitars" method="POST"> 
     <div class="input-group"> 
      <label>Item Name</label> 
      <div class="input-group"> 
       <input class="form-control" type="text" name="name" placeholder="Name"> 
      </div> 
      <label>Upload Image</label> 
      <div class="input-group"> 
     <span class="input-group-btn"> 
      <span class="btn btn-default btn-file"> 
       Browse… <input type="file" id="imgInp"> 
      </span> 
     </span> 
     <input type="text" class="form-control" readonly> 
    </div> 
    <img id="img-upload"/> 

     <div class="input-group"> 
      <button class="btn btn-lg btn-primary btn-block">Submit!</button> 
     </div> 

    <a href="/guitars">Go Back</a> 
</div> 

JS:

 $(document).ready(function() { 
      $(document).on('change', '.btn-file :file', function() { 
       var input = $(this), 
     label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); 
    input.trigger('fileselect', [label]); 
    }); 

    $('.btn-file :file').on('fileselect', function(event, label) { 

     var input = $(this).parents('.input-group').find(':text'), 
      log = label; 

     if(input.length) { 
      input.val(log); 
     } else { 
      if(log) alert(log); 
     } 

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

      reader.onload = function (e) { 
       $('#img-upload').attr('src', e.target.result); 
      } 

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

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

當提交表單,我希望它顯示已使用JS上傳的圖片,併爲它是「拯救」我的數據庫。

+0

_「當提交表單,我希望它顯示已使用JS上傳圖片」 _哪裏是''

提交缺省操作在代碼防止在問題? – guest271314

回答

0

你是什麼意思「發佈圖像到MongoDB」?您不應該將圖像保存在數據庫中。

你想要做的是當你上傳圖片時,將其存儲在服務器的公共訪問位置。您在數據庫中保存的內容不是圖像本身,而是圖像在服務器上的位置。

圖像存儲在服務器: /home/public/image.jpg

映像路徑保存在蒙戈DB: { path: '/home/public/image.jpg' }

當你回到你的HTML頁面,你只需要查詢的路徑Mongo DB中的圖像並將該值用作圖像標記中的源。

`<img src="${path}" />`