[英]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.我正在尝试创建一个 Dapp,让您可以使用 Nodejs 将图像上传到 IPFS。 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:而js代码是这样的:
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.我想做的是在文件输入更改时执行 function,以便我可以将其上传到某个 IPFS 节点。 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.第二个 function 在输入更改时触发,我想要的是将内容存储在某个变量中,以便在触发提交事件时可以获取它。 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.
为此,我创建了第一个 function setFile,因为从 reader.onloadend() 内部它没有检测到任何“文件”属性,但它也没有检测到 setFile。
How can I store the "f" content in somewhere that when a submit event is trigger I could get it back??我如何将“f”内容存储在某个地方,以便在触发提交事件时我可以将其取回?
Try converting it to base64 and storing the base64 string;尝试将其转换为 base64 并存储 base64 字符串; 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.我在想,如果你想在客户端进行,除了将它放在 canvas 中之外,我认为最好的选择是将它转换为 B64 并根据需要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.