![](/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.