Javascript

ipfs.files.add 承諾拋出錯誤

  • August 20, 2018

我正在嘗試使用ipfs.files.add(). 但是,我似乎無法弄清楚為什麼承諾會引發錯誤。

這是程式碼:

$(function() {
 $(window).load(function() {

   const IPFS = require("ipfs-api");
   const ipfs = IPFS("localhost", "5001", {protocol: "http"});

   var fileBuffer;
   var imageUpload = document.getElementById("input");
   imageUpload.addEventListener("change", handleFiles, false);

   function handleFiles() {
     console.log("File Chosen!");
     const reader = new FileReader;
     reader.readAsArrayBuffer(imageUpload.files[0]);
     console.log("Buffering...")
     reader.onload = function() {
       var arrayBuffer = reader.result;
       fileBuffer = new Uint8Array(arrayBuffer);
       console.log("Buffer: ", fileBuffer);
       ipfsUpload();
     }
   }

   function ipfsUpload() {
     console.log("Uploading...");
     ipfs.files.add(fileBuffer, (error, result) => {
       if (error || !result) {
         console.log("Error!");
       }
       else {
         console.log("Success!");
       }

     });
   }

 });
});

起初我以為我沒有正確連接到我的 IPFS 節點。但是,我在終端視窗中使用 node.js 完成了整個過程,並且成功了。所以我認為這可能與瀏覽器(Chrome)或某些依賴關係有關?

"dependencies": {
   "bootstrap": "^4.1.3",
   "browserify": "^16.2.2",
   "buffer": "^5.2.0",
   "ipfs": "^0.31.6",
   "ipfs-api": "^24.0.0",
   "jquery": "^3.3.1",
   "popper": "^1.0.1",
   "truffle": "^4.1.14",
   "web3": "^0.20.7"
 }

注意:我正在使用 Browserify 來捆綁我的所有依賴項。

編輯:列印實際錯誤後,我得到以下資訊:

TypeError: content.once is not a function
   at Multipart._pushFile (bundle.js:29092)
   at Multipart._maybeDrain (bundle.js:29056)
   at Multipart._transform (bundle.js:29048)
   at Multipart.Transform._read (bundle.js:107644)
   at Multipart.Transform._write (bundle.js:107632)
   at doWrite (bundle.js:108104)
   at writeOrBuffer (bundle.js:108093)
   at Multipart.Writable.write (bundle.js:108010)
   at eachSeries (bundle.js:29443)
   at bundle.js:23065

所以我能夠通過使用Buffer.from()我的變數fileBufferin來解決這個問題ipfs.files.add(),給我以下程式碼:

ipfs.files.add(Buffer.from(fileBuffer), function(error, result) {
       if (error || !result) {
         console.log(error);
       }
       else {
         console.log("Success!");
       }
     });

引用自:https://ethereum.stackexchange.com/questions/56873