【问题标题】:How do I convert a buffer into BSON format?如何将缓冲区转换为 BSON 格式?
【发布时间】:2022-07-05 21:28:12
【问题描述】:

我正在尝试将文件(我打开并读入缓冲区)转换为有效的 BSON 格式。

我编写客户端以发出需要两个字段的请求;

  1. 文件名
  2. 文件(缓冲区)

这里的问题是我似乎无法在这里成功转换。

另一个问题是,在进行此转换后,是否可以将此 BSON 请求转换为缓冲区,因为这是 curl(Easy) crate 用于发出请求的类型(即来自终端而不是浏览器的请求表格)

这是我发出此请求的代码

// It takes in a file path.
fn send_file_post(file_from_arg: &str) -> tide::Result {

    // initialise the connection to the server
    let mut easy = Easy::new();
    easy.url("http://0.0.0.0:8080/hi").unwrap();

    // Opens and reads the file path
    let mut file = File::open(file_from_arg)?;
    let mut buf = [0; 1096];

    // reads file into buffer
    loop {
        let n = file.read(&mut buf)?;

        if n == 0 {
            // reached end of file
            break;
        }

        // easy.write_all(&buf[..n])?;
    }


// attempted bson format
    let bson_data: Bson = bson!({
    "name": file_from_arg,
    "file": buf
});

// sending the request, this is only sending the file for now, I want to send a bson format that is buffered (in a buffer/bytes format) 
    easy.post_fields_copy(&buf).unwrap();
    easy.write_function(|data| {
        stdout().write_all(data).unwrap();
        Ok(data.len())
    })
    .unwrap();

    println!(" oh hi{:?}", easy.perform().unwrap());
    Ok(format!("okay sent!").into())
}

【问题讨论】:

    标签: rust server client bson


    【解决方案1】:

    我意识到 serde_json 可以转换为 vec!方法,如果不一样可以比作字节。所以我将文件转换为字节并将其作为缓冲区发送。函数如下所示。

    
    // It takes in a file path.
    fn send_file_post(file_from_arg: &str, port_addr: &str) -> tide::Result {
        // initialise
        let mut easy = Easy::new();
        let port = format!("{}/hi", port_addr);
        easy.url(&port).unwrap();
        
    // reads file path
        let file = std::fs::read(file_from_arg)?;
    
    
        //extracts name of the file from file path
        let (.., file_name) = file_from_arg
            .rsplit_once(std::path::MAIN_SEPARATOR)
            .unwrap();
    
    // creates the necessary type to send the file in bytes
        let new_post = FileSearch {
            file_name: file_name.to_string(),
            file_bytes: file,
        };
    
    // Unwrap into a vector, which can be likened to bytes
        let send_file_body_req = serde_json::to_vec(&new_post).unwrap();
    
        // make and send request
        easy.post(true).unwrap();
        easy.post_field_size(send_file_body_req.len() as u64).unwrap();
    
        let mut transfer = easy.transfer();
        transfer
            .read_function(|buf| Ok(send_file_body_req.as_slice().read(buf).unwrap_or(0)))
            .unwrap();
        transfer.perform().unwrap();
    
        Ok(format!("okay sent!").into())
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2022-11-04
      • 2022-08-05
      • 2020-04-26
      • 2016-03-09
      • 1970-01-01
      • 2018-06-29
      相关资源
      最近更新 更多