【问题标题】:How do I upload a file given its absolute path in rust? [duplicate]给定 rust 中的绝对路径,如何上传文件? [复制]
【发布时间】:2020-02-17 23:00:13
【问题描述】:

我的目标是使用 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" }

我参考 this回答并阅读official documentation,都是徒劳的。

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

【问题讨论】:

    标签: command-line rust ipfs


    【解决方案1】:

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

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

    【讨论】:

    • 如何让我的代码接受输入并上传它?我尝试对这些值进行硬编码并且它可以工作,但我无法使用接受输入的变量并使用它来上传文件。
    • @AviralSrivastava 您只需要在将路径传递给命令时(或之前)删除换行符。例如,用.arg(file_path.trim_end()) 替换.arg(file_path) 应该可以工作。
    • 在答案中添加这个以便我可以接受。
    猜你喜欢
    • 2011-05-09
    • 2017-10-22
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多