在IPFS.ADD()方法中使用带有EJS的IPF在上传文件中获取错误

发布于 2025-02-12 17:51:04 字数 10942 浏览 0 评论 0原文

我正在尝试使用EJS应用将文件上传到IPF。我遇到了很多发布的问题,但是我还没有看到像我遇到的问题。

当我们使用简单的字符串“ Hello World” 使用ipfs.add()方法时,它仍然适用于其他人,但就我而言,它会丢弃错误。

这是我尝试上传文件的代码:

上传文件代码(upload.ejs):

<div class="card">
            <h5 class="card-header">Upload Document to IPFS</h5>
            <div class="card-body">
                <form action="/ipfs" method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="form-group col-10">
                            <input type="file" name="filetoupload" class="form-control">
                        </div>
                        <div class="form-group col">
                            <button type="submit" class="btn btn-primary">UPLOAD</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

app.js file:

const fs = require('fs')
const express = require("express");
const cors = require('cors');
const path = require('path');
const fileupload = require('express-fileupload');
const { create } = require("ipfs-http-client");

const app = express();

app.use(fileupload());
app.use(cors());
app.use(express.static(path.join(__dirname,'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.set('views', './views');
app.set('view engine', 'ejs');

app.listen(8010, () => {
  console.log("Application started and Listening on port 8010");
});

app.get("/", (req, res) => {
  res.render("home");
});


const ipfs = create({host:'localhost',port:6001,protocol:'http'});
app.get("/ipfs/:hashcode", async function(req, res) {
    const hashcode = req.params.hashcode;
    res.setHeader('Content-Type','application/json');
    let result = false;
    if (hashcode) {
        const stream = ipfs.cat(hashcode);
        let data = ''

        for await (const chunk of stream) {
        // chunks of data are returned as a Buffer, convert it back to a string
        data += chunk.toString()
        }
        result = true;
        res.json({
            'success': result,
            'data': data
        });

            
        
    } else {
        res.json({
            'success': result,
            'data': ''
        });
    }
  
});

app.post("/ipfs", (req, res) => {
    
    const file = req.files.filetoupload;
    const filename = req.files.filetoupload.name;

    console.log("here")
    const filepath = 'files/' + filename;

    file.mv(filepath, async(err) => {
        if(err){
            console.log("ERROR: Upload File Error!");
            return res.status(500).send(err);
        }
        const hashcode = await addFile(filename,filepath);
        console.log("HHHHAAAAAAAAAAAAAAAAAAASSSSSSSSSSSSHHHHHH...."+hashcode); // here i am gettin undefined
        fs.unlink(filepath, (err  => {
            if(err) console.log(err);
        }))
        res.render("upload",{filename, hashcode});
    })
    
    
});
// ipfs api: https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options
const addFile = async(filename,filepath) => {

    try {
        const file = fs.readFileSync(filepath);
        console.log("------------------(Here Before await)--------------------\n");
        // const added = await ipfs.add(file);
        // const added = await ipfs.add({path: filename, content:file});
        const added = await ipfs.add("hello world"); // here i am getting error
        console.log("------------------(Here After await)--------------------\n"); // after error this lone is ignored
        // console.info(added);
        return added.cid.toString();
    } catch (err){
        console.log(err);
    }
    
}

我在应用程序中使用addfile()方法。

version: '3'
services:
  ipfs:
    image: ipfs/go-ipfs:latest
    container_name: ipfs_host
    volumes:
      - ./export:/export
      - ./ipfs_data:/data/ipfs
    ports:
      - '4001:4001'
      - '4001:4001/udp'
      - '127.0.0.1:8080:8080'
      - '127.0.0.1:7010:7010'

​ 在提出@discordian的建议后,更新了错误快照 @discordian跟踪我没有Docker-Compose,但是之后我仍会遇到错误。

abidullah@abidullah:~/Desktop/BC Project/document-verification-dapp$ ./start.sh
Building images
Traceback (most recent call last):
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
FileNotFoundError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "requests/adapters.py", line 449, in send
  File "urllib3/connectionpool.py", line 727, in urlopen
  File "urllib3/util/retry.py", line 410, in increment
  File "urllib3/packages/six.py", line 734, in reraise
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker/api/client.py", line 214, in _retrieve_server_version
  File "docker/api/daemon.py", line 181, in version
  File "docker/utils/decorators.py", line 46, in inner
  File "docker/api/client.py", line 237, in _get
  File "requests/sessions.py", line 543, in get
  File "requests/sessions.py", line 530, in request
  File "requests/sessions.py", line 643, in send
  File "requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker-compose", line 3, in <module>
  File "compose/cli/main.py", line 81, in main
  File "compose/cli/main.py", line 200, in perform_command
  File "compose/cli/command.py", line 70, in project_from_options
  File "compose/cli/command.py", line 153, in get_project
  File "compose/cli/docker_client.py", line 43, in get_client
  File "compose/cli/docker_client.py", line 170, in docker_client
  File "docker/api/client.py", line 197, in __init__
  File "docker/api/client.py", line 222, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
[29229] Failed to execute script docker-compose
Traceback (most recent call last):
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
FileNotFoundError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "requests/adapters.py", line 449, in send
  File "urllib3/connectionpool.py", line 727, in urlopen
  File "urllib3/util/retry.py", line 410, in increment
  File "urllib3/packages/six.py", line 734, in reraise
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker/api/client.py", line 214, in _retrieve_server_version
  File "docker/api/daemon.py", line 181, in version
  File "docker/utils/decorators.py", line 46, in inner
  File "docker/api/client.py", line 237, in _get
  File "requests/sessions.py", line 543, in get
  File "requests/sessions.py", line 530, in request
  File "requests/sessions.py", line 643, in send
  File "requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker-compose", line 3, in <module>
  File "compose/cli/main.py", line 81, in main
  File "compose/cli/main.py", line 200, in perform_command
  File "compose/cli/command.py", line 70, in project_from_options
  File "compose/cli/command.py", line 153, in get_project
  File "compose/cli/docker_client.py", line 43, in get_client
  File "compose/cli/docker_client.py", line 170, in docker_client
  File "docker/api/client.py", line 197, in __init__
  File "docker/api/client.py", line 222, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
[29234] Failed to execute script docker-compose
install libraries
mkdir: cannot create directory ‘files’: File exists
npm ERR! code ENOTEMPTY
npm ERR! syscall rename
npm ERR! path /home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/iso-random-stream
npm ERR! dest /home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/.iso-random-stream-CBO0cinM
npm ERR! errno -39
npm ERR! ENOTEMPTY: directory not empty, rename '/home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/iso-random-stream' -> '/home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/.iso-random-stream-CBO0cinM'

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/abidullah/.npm/_logs/2022-07-04T18_52_00_411Z-debug-0.log
start service
Application started and Listening on port 8010

I am trying to upload a file to ipfs using ejs app. I have go to a lot of posted problems but i have not seen a problem like i am getting.

when we use ipfs.add() method with a simple string "Hello World" it still worked for others but in my case it is throwing an error.

This is the code where I try to upload the file:

upload file code (upload.ejs):

<div class="card">
            <h5 class="card-header">Upload Document to IPFS</h5>
            <div class="card-body">
                <form action="/ipfs" method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="form-group col-10">
                            <input type="file" name="filetoupload" class="form-control">
                        </div>
                        <div class="form-group col">
                            <button type="submit" class="btn btn-primary">UPLOAD</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

app.js file:

const fs = require('fs')
const express = require("express");
const cors = require('cors');
const path = require('path');
const fileupload = require('express-fileupload');
const { create } = require("ipfs-http-client");

const app = express();

app.use(fileupload());
app.use(cors());
app.use(express.static(path.join(__dirname,'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.set('views', './views');
app.set('view engine', 'ejs');

app.listen(8010, () => {
  console.log("Application started and Listening on port 8010");
});

app.get("/", (req, res) => {
  res.render("home");
});


const ipfs = create({host:'localhost',port:6001,protocol:'http'});
app.get("/ipfs/:hashcode", async function(req, res) {
    const hashcode = req.params.hashcode;
    res.setHeader('Content-Type','application/json');
    let result = false;
    if (hashcode) {
        const stream = ipfs.cat(hashcode);
        let data = ''

        for await (const chunk of stream) {
        // chunks of data are returned as a Buffer, convert it back to a string
        data += chunk.toString()
        }
        result = true;
        res.json({
            'success': result,
            'data': data
        });

            
        
    } else {
        res.json({
            'success': result,
            'data': ''
        });
    }
  
});

app.post("/ipfs", (req, res) => {
    
    const file = req.files.filetoupload;
    const filename = req.files.filetoupload.name;

    console.log("here")
    const filepath = 'files/' + filename;

    file.mv(filepath, async(err) => {
        if(err){
            console.log("ERROR: Upload File Error!");
            return res.status(500).send(err);
        }
        const hashcode = await addFile(filename,filepath);
        console.log("HHHHAAAAAAAAAAAAAAAAAAASSSSSSSSSSSSHHHHHH...."+hashcode); // here i am gettin undefined
        fs.unlink(filepath, (err  => {
            if(err) console.log(err);
        }))
        res.render("upload",{filename, hashcode});
    })
    
    
});
// ipfs api: https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options
const addFile = async(filename,filepath) => {

    try {
        const file = fs.readFileSync(filepath);
        console.log("------------------(Here Before await)--------------------\n");
        // const added = await ipfs.add(file);
        // const added = await ipfs.add({path: filename, content:file});
        const added = await ipfs.add("hello world"); // here i am getting error
        console.log("------------------(Here After await)--------------------\n"); // after error this lone is ignored
        // console.info(added);
        return added.cid.toString();
    } catch (err){
        console.log(err);
    }
    
}

I am getting in addFile() method in app.js const added = await ipfs.add("hello world");

Docker Compose file

version: '3'
services:
  ipfs:
    image: ipfs/go-ipfs:latest
    container_name: ipfs_host
    volumes:
      - ./export:/export
      - ./ipfs_data:/data/ipfs
    ports:
      - '4001:4001'
      - '4001:4001/udp'
      - '127.0.0.1:8080:8080'
      - '127.0.0.1:7010:7010'

Error Snap (Updated):
The error snap is updated after some suggestion of @discordian
@discordian trace that i have no docker-compose, but after that i am still getting the error.

abidullah@abidullah:~/Desktop/BC Project/document-verification-dapp$ ./start.sh
Building images
Traceback (most recent call last):
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
FileNotFoundError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "requests/adapters.py", line 449, in send
  File "urllib3/connectionpool.py", line 727, in urlopen
  File "urllib3/util/retry.py", line 410, in increment
  File "urllib3/packages/six.py", line 734, in reraise
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker/api/client.py", line 214, in _retrieve_server_version
  File "docker/api/daemon.py", line 181, in version
  File "docker/utils/decorators.py", line 46, in inner
  File "docker/api/client.py", line 237, in _get
  File "requests/sessions.py", line 543, in get
  File "requests/sessions.py", line 530, in request
  File "requests/sessions.py", line 643, in send
  File "requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker-compose", line 3, in <module>
  File "compose/cli/main.py", line 81, in main
  File "compose/cli/main.py", line 200, in perform_command
  File "compose/cli/command.py", line 70, in project_from_options
  File "compose/cli/command.py", line 153, in get_project
  File "compose/cli/docker_client.py", line 43, in get_client
  File "compose/cli/docker_client.py", line 170, in docker_client
  File "docker/api/client.py", line 197, in __init__
  File "docker/api/client.py", line 222, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
[29229] Failed to execute script docker-compose
Traceback (most recent call last):
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
FileNotFoundError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "requests/adapters.py", line 449, in send
  File "urllib3/connectionpool.py", line 727, in urlopen
  File "urllib3/util/retry.py", line 410, in increment
  File "urllib3/packages/six.py", line 734, in reraise
  File "urllib3/connectionpool.py", line 677, in urlopen
  File "urllib3/connectionpool.py", line 392, in _make_request
  File "http/client.py", line 1277, in request
  File "http/client.py", line 1323, in _send_request
  File "http/client.py", line 1272, in endheaders
  File "http/client.py", line 1032, in _send_output
  File "http/client.py", line 972, in send
  File "docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker/api/client.py", line 214, in _retrieve_server_version
  File "docker/api/daemon.py", line 181, in version
  File "docker/utils/decorators.py", line 46, in inner
  File "docker/api/client.py", line 237, in _get
  File "requests/sessions.py", line 543, in get
  File "requests/sessions.py", line 530, in request
  File "requests/sessions.py", line 643, in send
  File "requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker-compose", line 3, in <module>
  File "compose/cli/main.py", line 81, in main
  File "compose/cli/main.py", line 200, in perform_command
  File "compose/cli/command.py", line 70, in project_from_options
  File "compose/cli/command.py", line 153, in get_project
  File "compose/cli/docker_client.py", line 43, in get_client
  File "compose/cli/docker_client.py", line 170, in docker_client
  File "docker/api/client.py", line 197, in __init__
  File "docker/api/client.py", line 222, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
[29234] Failed to execute script docker-compose
install libraries
mkdir: cannot create directory ‘files’: File exists
npm ERR! code ENOTEMPTY
npm ERR! syscall rename
npm ERR! path /home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/iso-random-stream
npm ERR! dest /home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/.iso-random-stream-CBO0cinM
npm ERR! errno -39
npm ERR! ENOTEMPTY: directory not empty, rename '/home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/iso-random-stream' -> '/home/abidullah/Desktop/BC Project/document-verification-dapp/client/node_modules/.iso-random-stream-CBO0cinM'

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/abidullah/.npm/_logs/2022-07-04T18_52_00_411Z-debug-0.log
start service
Application started and Listening on port 8010

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文