首页 > 解决方案 > 给定 rust 中的绝对路径,如何上传文件?

问题描述

我的目标是使用 Rust 编程语言在 ipfs.io 上上传文件。我正在触发一个命令行工具来执行此操作,并且该命令本身可以工作,但是当使用 Rust 实现时,它会失败。

实际的命令是:

➜  ~ ipfs add ~/dev/learning-rust/upload-file-to-ipfs/src/main.rs
added QmPUGDCiLvjEiETVDVMHqgJ8xxtQ5Hu7YEMzFqRfE8vDfq main.rs

现在,我的 Rust 代码是:

use std::io;
use std::process::Command;


fn main() {
    // ask user to provide the file path to be uploaded on ipfs
    println!("Please enter the file path to upload on IPFS: ");
    let mut file_path = String::new();
    io::stdin()
        .read_line(&mut file_path)
        .expect("Failed to read temperature.");
    // uploading a file
    let output = Command::new("ipfs")
        .arg("add")
        .arg(file_path)
        .output()
        .expect("ipfs command failed to start");
    println!("Output is: {:?}", output);
    // println!("The hash digest is: {:?}", output.stdout);
}

这失败并出现以下错误:

Output is: Output { status: ExitStatus(ExitStatus(256)), stdout: "", stderr: "Error: lstat /Users/aviralsrivastava/dev/learning-rust/upload-file-to-ipfs/src/main.rs\n: no such file or directory\n\nUSAGE\n  ipfs add <path>... - Add a file or directory to ipfs.\n\n  ipfs add [--recursive | -r] [--quiet | -q] [--quieter | -Q] [--silent] [--progress | -p] [--trickle | -t] [--only-hash | -n] [--wrap-with-directory | -w] [--hidden | -H] [--chunker=<chunker> | -s] [--pin=false] [--raw-leaves] [--nocopy] [--fscache] [--cid-version=<cid-version>] [--] <path>...\n\n  Adds contents of <path> to ipfs. Use -r to add directories (recursively).\n\nUse \'ipfs add --help\' for more information about this command.\n\n" }

我参考这个来回答和阅读官方文档,都是徒劳的。

如何上传给定绝对和/或相对路径的文件并在打印语句中返回哈希?

标签: command-linerustipfs

解决方案


您的问题不在于Commandwith read_line,它将读取所有字节,包括换行符(请参见此处)。因此,您的路径最终包含换行符,这就是找不到文件的原因。

要解决此问题,您需要确保文件路径不包含尾随换行符,例如在将其传递给命令之前对其调用trim_end 。


推荐阅读