Connecting Html to IPFS and upload a file

111 Views Asked by At

I have some problem of connecting my html to IPFS, I use <script src="https://unpkg.com/[email protected]/dist/index.min.js"></script> instead of npm install(Because npm install seems can't run on chrome liveserver) and here is my html and js below: TEST.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IPFS File Upload</title>   
    <script src="https://unpkg.com/[email protected]/dist/index.min.js"></script>
</head>
<body>
    <input type="file" id="fileInput">
    <button id="uploadButton">Upload File to IPFS</button>
    <div id="result"></div>

    <script type="module" src="./js/TEST.js"></script>
</body>
</html>

TEST.js

import { require } from 'https://unpkg.com/[email protected]/dist/index.min.js';

document.addEventListener('DOMContentLoaded', async () => {
    const fileInput = document.getElementById('fileInput');
    const uploadButton = document.getElementById('uploadButton');
    const resultDiv = document.getElementById('result');

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

        if (!file) {
            alert('Please select a file to upload.');
            return;
        }
        const IPFS = require('ipfs')
        const ipfs = await IPFS.create(); // Create an instance of Ipfs

        try {
            const { cid } = await ipfs.add(file);

            const ipfsUrl = `https://ipfs.io/ipfs/${cid.toString()}`;
            resultDiv.innerHTML = `<p>IPFS URL: <a href="${ipfsUrl}" target="_blank">${ipfsUrl}</a></p>`;
        } catch (error) {
            console.error('Error uploading to IPFS:', error);
            resultDiv.innerHTML = '<p>Error uploading to IPFS. Check your IPFS node and try again.</p>';
        }
    });
});

It got error message: Uncaught SyntaxError: The requested module does not provide an export named 'require'

I tried to connect it to IPFS with multiple methods but all of them lead to similar errors, such as Ipfs, window.IpfsHttpClient is not defined at HTMLButtonElement. Are there any optimal solution to it?

0

There are 0 best solutions below