![](/img/trans.png)
[英]How do I store the content of a variable for later use in other function (Javascript)
[英]How to store file input content in a variable for later use in Nodejs?
我正在尝试创建一个 Dapp,让您可以使用 Nodejs 将图像上传到 IPFS。 我创建了下一个表格:
<form id="upload_form">
<input id="upload_image" type="file"></input>
<input type="submit"/>
</form>
而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();
});
我想做的是在文件输入更改时执行 function,以便我可以将其上传到某个 IPFS 节点。 问题是我真的不知道该怎么做。 我试过这个:
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);
}
}),
第二个 function 在输入更改时触发,我想要的是将内容存储在某个变量中,以便在触发提交事件时可以获取它。 为此,我创建了第一个 function setFile,因为从 reader.onloadend() 内部它没有检测到任何“文件”属性,但它也没有检测到 setFile。
我如何将“f”内容存储在某个地方,以便在触发提交事件时我可以将其取回?
尝试将其转换为 base64 并存储 base64 字符串; 您可以在需要时将其编码回来。
var fs = require('fs');
var base64img = fs.readFileSync(file, 'base64');
我在想,如果你想在客户端进行,除了将它放在 canvas 中之外,我认为最好的选择是将它转换为 B64 并根据需要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.