如何将图片文件网址上传到indexedDB以在页面上呈现

时间:2018-09-05 17:00:18

标签: javascript jquery database indexeddb

目标是当我添加客户时也希望能够上传图片。在主要客户页面上,它将列出所有客户和客户的缩略图。

当前,当我将图像上传到indexedDB时,它没有采用正确的URL。在我当前的学习项目中,当我上传图片时,它会上传以下URL地址:

C:\fakepath\01-gel-nail-designs-thecuddl.jpg

我不确定为什么会一直给出C:\fakepath而不是正确的路径,因此当它在主要客户页面上呈现时,它只是残破的图像填充物。

这是我的index.html:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->


    <title>Customer Manager</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/style.css" rel="stylesheet">
  </head>
  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Customer Manager v0.1</a>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li class="active"><a href="#">Customers <span class="sr-only">(current)</span></a></li>
            <li><a href="add.html">Add Customer</a></li>
            <li><a onclick="clearCustomers()" class="danger" href="#">Clear Customers</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h1 class="page-header">Customers</h1>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Name</th>
                  <th>Email Address</th>
                  <th></th>
                </tr>
              </thead>
              <tbody id="customers">

              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
    <script src="../../assets/js/vendor/holder.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>

这是我的add.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->


    <title>Add Customer</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/style.css" rel="stylesheet">
  </head>
  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Customer Manager v0.1</a>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li class="active"><a href="#">Customers <span class="sr-only">(current)</span></a></li>
            <li><a href="add.html">Add Customer</a></li>
            <li><a class="danger" href="#">Clear Customers</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h1 class="page-header">Add Customer</h1>
          <form role="form" onsubmit="addCustomer()">
              <div class="form-group">
                <label>Customer Name</label>
                <input type="text" id="name" class="form-control" placeholder="Enter Name">
              </div>
              <div class="form-group">
                <label>Customer Email</label>
                <input type="email" id="email" class="form-control" placeholder="Enter Email">
              </div>
              <input type="file" id="imageSelector" multiple="multiple" />
              <button type="submit" class="btn btn-default">Add Customer</button>
        </form>
        </div>
      </div>
    </div>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
    <script src="../../assets/js/vendor/holder.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>

这是我的main.js:

$(document).ready(function(){
    //Open database
    var request = indexedDB.open('customermanager',1);

    request.onupgradeneeded = function(e){
        var db = e.target.result;

        if(!db.objectStoreNames.contains('customers')){
              var os = db.createObjectStore('customers',{keyPath: "id", autoIncrement:true});
                //Create Index for Name
                os.createIndex('name','name',{unique:false});
        }
    }


    //Success
    request.onsuccess = function(e){
        console.log('Success: Opened Database...');
        db = e.target.result;
        //Show Customers
        showCustomers();
    }

    //Error
    request.onerror = function(){
        console.log('Error: Could Not Open Database...');
    }
});

//Add Customer
function addCustomer(){
    var name = $('#name').val();
    var email = $('#email').val();
    var image = $('#imageSelector').getAttribute('src');



    var transaction = db.transaction(["customers"],"readwrite");
    //Ask for ObjectStore
    var store = transaction.objectStore("customers");

    //Define Customer
    var customer = {
        name: name,
        email: email,
        image: image
    }

    //Perform the Add
    var request = store.add(customer);

    //Success
    request.onsuccess = function(e){
        window.location.href="index.html";
    }

    //Error
    request.onerror = function(e){
        alert("Customer was not added");
        console.log('Error', e.target.error.name);
    }
}

//Display Customers
function showCustomers(e){
    var transaction = db.transaction(["customers"],"readonly");
    //Ask for ObjectStore
    var store = transaction.objectStore("customers");
    var index = store.index('name');

    var output = '';
    index.openCursor().onsuccess = function(e){
        var cursor = e.target.result;
        if(cursor){
            output += "<tr id='customer_"+cursor.value.id+"'>";
            output += "<td>"+cursor.value.id+"</td>";
            output += "<td><span class='cursor customer' contenteditable='true' data-field='name' data-id='"+cursor.value.id+"'>"+cursor.value.name+"</span></td>";
            output += "<td><span class='cursor customer' contenteditable='true' data-field='email' data-id='"+cursor.value.id+"'>"+cursor.value.email+"</span></td>";
              output += "<td><img class='thumbnail' src='"+cursor.value.id+"'></img></td>";
            output += "<td><a onclick='removeCustomer("+cursor.value.id+")' href=''>Delete</a></td>";
            output += "</tr>";
            cursor.continue();
        }
        $('#customers').html(output);
    }
}

//Delete a Customer
function removeCustomer(id){
    var transaction = db.transaction(["customers"],"readwrite");
    //Ask for ObjectStore
    var store = transaction.objectStore("customers");

    var request = store.delete(id);

    //Success
    request.onsuccess = function(){
        console.log('Customer '+id+' Deleted');
        $('customer_'+id).remove();
    }

    //Error
    request.onerror = function(e){
        alert("The customer was not removed")
        console.log('Error', e.target.error.name);
    }
}

//Clear All Customers
function clearCustomers(){
    indexedDB.deleteDatabase('customermanager');
    window.location.href="index.html";
}

//Update Customers
$('#customers').on('blur','.customer',function(){
    //Newly entered text
    var newText = $(this).html();
    //Field
    var field = $(this).data('field');
    //Customer ID
    var id = $(this).data('id');

    //Get Transaction
    var transaction = db.transaction(["customers"],"readwrite");
    //Ask for ObjectStore
    var store = transaction.objectStore("customers");

    var request = store.get(id);

    request.onsuccess = function(){
        var data = request.result;
        if(field == 'name'){
           data.name = newText;
        } else if(field == 'email'){
            data.email = newText;
        }

        //Store Updated Text
        var requestUpdate = store.put(data);

        requestUpdate.onsuccess = function(){
            console.log('Customer field updated...');
        }

        requestUpdate.onerror = function(){
            console.log('Customer field NOT updated...');
        }
    }
});

这是indexedDB在控制台中的外观及其在index.html中的显示方式的图像:

first image

这是我的add.html外观的图片:

second image

任何指导将不胜感激。

更新1

基于一些其他研究,由于安全原因,我将无法使用我拥有的代码来完成我想做的事情,如果不使用其他方法,我将无法找到真正的路径。我正在努力从此链接https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/找到一种实现示例的方法。

1 个答案:

答案 0 :(得分:1)

这是一个不完整的答案,只是一些注意事项。如果您坚持使用indexedDB,则可能要将上传的文件作为blob存储在indexedDB中。接下来,您要使用URL.createObjectURL将图片的src设置为斑点的url。请记住,某些浏览器在存储Blob方面存在问题,因此是否有效取决于您所支持的浏览器。

以下是一些入门的粗略代码:

addEventListener('DOMContentLoaded', event => {
  attachUploadHandler();
});

function attachUploadHandler() {
  const input = document.querySelector('#uploader');
  input.setAttribute('type', 'file');
  input.setAttribute('accept', 'image/png, image/gif, image/jpeg');
  input.onchange = onchange;
}

function openDb() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(name, version);
    request.onupgradeneeded = onupgradeneeded;
    request.onsuccess = _ => resolve(request.result);
    request.onerror = _ => reject(request.error);
  });
}

function onupgradeneeded(event) {
  const conn = event.target.result;
  conn.createObjectStore('store');
}

// Handle file uploader change event 
async function onchange(event) {
  const files = event.target.files;

  const conn = await openDb();
  await new Promise((resolve, reject) => {
    const tx = conn.transaction('store', 'readwrite');
    tx.oncomplete = resolve;
    tx.onerror = _ => reject(new Error('file storage error'));

    const store = tx.objectStore('store');

    for(const file of files) {
      store.put(file);
    }
  });
  conn.close();
}

接下来,您可能想在图像存储中使用脱机键,然后将图像ID存储在客户存储中。然后加载所有客户,并为每个客户查询图像存储中的相应图像。

此刻,我忘记了如何做离线读/写操作,因此您必须弄清楚这一点。

function getCustomers(conn) {
  return new Promise((resolve, reject) {
    const tx = conn.transaction(['customers', 'images']);
    tx.oncomplete = resolve(customers);
    const customer_store = tx.objectStore('customers');
    const image_store = tx.objectStore('images');

    function set_customer_image(customer, event) {
      customer.image_blob = event.target.result;
    }

    const customers_request = customer_store.getAll();
    customers_request.onsuccess = event => {
      const customers = customers_request.result;
      for(const customer of customers) {
        const image_request = image_store.get(customer.image_id);
        image_request.onsuccess = set_customer_image.bind(image_request, customer);          
      }
    };
  });
}

然后,在渲染时,技巧是为每个blob使用URL.createObjectURL,并将image_element.src设置为该地址。

function renderCustomers(customers) {
  const image_placeholder_url_string = 'customer-image-placeholder.gif';

  for(const customer of customers) {
     const tr = new HTMLTableRowElement();

     // now, the key part for the customer image cell
     const td = new HTMLTableCellElement();
     const image = new HTMLImageElement();
     if(customer.image_blob) {
       image.src = URL.createObjectURL(customer.image_blob);
     } else {
       image.src = image_placeholder_url_string;
     }

     td.appendChild(image);
     tr.appendChild(td);
  }
}