const ipfs = new IPFS({ host: '127.0.0.1', port: 5001, protocol: 'http' });

$(document).ready(function () {
const fileInput = document.getElementById('fileInput');
const uploadButton = document.getElementById('uploadButton');
const fileHash = document.getElementById('fileHash');
const hashForDownload = document.getElementById('hashForDownload');
const downloadButton = document.getElementById('downloadButton');

uploadButton.addEventListener('click', function () {
const file = fileInput.files[0];

if (!file) {
alert('Please select a file to upload.');
return;
}

var reader = new FileReader();

reader.onload = function () {
var fileData = reader.result;

const buffer = new TextEncoder().encode(fileData);

ipfs.add(buffer, function (err, result) {
if (!err) {
const ipfsHash = result[0].hash;
fileHash.value = ipfsHash;
alert('File uploaded to IPFS with hash: ' + ipfsHash);
} else {
console.error('Error uploading file to IPFS:', err);
}
});
};

reader.readAsArrayBuffer(file);
});

downloadButton.addEventListener('click', function () {
const ipfsHash = hashForDownload.value;

if (!ipfsHash) {
alert('Please enter an IPFS Hash to download a file.');
return;
}

ipfs.cat(ipfsHash, function (err, data) {
if (!err) {
const blob = new Blob([data]);
const url = window.URL.createObjectURL(blob);

const downloadLink = document.getElementById('downloadLink');
downloadLink.href = url;
downloadLink.download = 'downloaded_file';
downloadLink.style.display = 'block';
} else {
alert('Error downloading file from IPFS:', err);
}
});
});
});
app.js

Oct 29, 2023, 10:39 AM
thanks
Oct 29, 2023, 11:33 AM

© 2024 Draquery.com All rights reserved.