javascriptnode.jsipfsjs-ipfs

How to store file input content in a variable for later use in Nodejs?


I'm trying to create a Dapp that let you upload an image to IPFS with Nodejs. I created the next form:

<form id="upload_form">
    <input id="upload_image" type="file"></input>
    <input type="submit"/>
</form>

And js code is like this:

import Web3 from "web3";
import amongAllArtifact from "../../build/contracts/AmongAll.json";

//const ipfs = require("ipfs-http-client");

const App = {
  web3: null,
  account: null,
  contract: null,

  file: null,


  start: async function() {
    const { web3 } = this;

    try {
      // get contract instance
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = contractArtifact.networks[networkId];
      this.contract = new web3.eth.Contract(
        contractArtifact.abi,
        deployedNetwork.address,
      );

      // get accounts
      const accounts = await web3.eth.getAccounts();
      this.account = accounts[0];

      this.refreshAddress();

    } catch (error) {
      console.error("Could not connect to contract or chain.");
    }
  },

};

window.App = App;

window.addEventListener("load", function() {
  
  App.start();
});

What I wanted to do is to execute a function when the file input changes so that I could upload it to some IPFS node. The thing is that I really dont know how to do it. I've tried this:

setFile: async function(file){

    this.file(file);

  },


  capture_change: document.getElementById('upload_image').addEventListener('change', function(event) {
    
    event.preventDefault();
    console.log("procesando imgane...");
    
    var f = event.target.files[0];

    console.log("files: ", f)

    const reader = new window.FileReader();
    reader.readAsArrayBuffer(f)
    
    reader.onloadend = () => {
      
      setFile(Buffer(reader.result));
      console.log(this.file);
    }
  }),

The second function trigger when the input changes and what I wantted was to store the content in some variable so that I could get it when the submit event was triggered. For that I created the first function setFile, because from inside reader.onloadend() it doesnt detect any "file" attribute, but it doesnt detect setFile either.

How can I store the "f" content in somewhere that when a submit event is trigger I could get it back??


Solution

  • Try converting it to base64 and storing the base64 string; you can encode it back whenever you need.

    var fs = require('fs');
    var base64img = fs.readFileSync(file, 'base64');
    

    I'm thinking if you want to do it client side, aside from placing it in a canvas the best option I believe is convert it to B64 and use it as you need.