首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将缓冲区转换为BSON格式?

如何将缓冲区转换为BSON格式?
EN

Stack Overflow用户
提问于 2022-05-25 13:50:46
回答 1查看 159关注 0票数 0

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

我写的客户端提出的请求,需要两个字段;

file

  • File(buffer)

  1. 名称

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

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

这是我提出这个请求的代码

代码语言:javascript
复制
// 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())
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-05 13:28:12

我意识到serde_json有一个转换到vec!方法,可以将其比作字节(如果不是相同的话)。因此,我将文件转换为字节,并将其作为缓冲区发送。这是如下所示的函数。

代码语言:javascript
复制
// 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())
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72378902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档