代码之家  ›  专栏  ›  技术社区  ›  Explosion Pills

使用rusoto将字符串上载到S3

  •  1
  • Explosion Pills  · 技术社区  · 6 年前

    我在用 rusoto S3创建一个JSON字符串并将该字符串上载到S3存储桶。我可以创建字符串,但Rusoto的S3 PutObjectRequest 需要一个 StreamingBody 我不知道如何创建 流体 从一个字符串或这是否真的是必要的。

    extern crate json;
    extern crate rusoto_core;
    extern crate rusoto_s3;
    extern crate futures;
    
    use rusoto_core::Region;
    use rusoto_s3::{S3, S3Client, PutObjectRequest};
    
    fn main() {
        let mut paths = Vec::new();
        paths.push(1);
        let s3_client = S3Client::new(Region::UsEast1);
        println!("{}", json::stringify(paths));
        s3_client.put_object(PutObjectRequest {
            bucket: String::from("bucket"),
            key: "@types.json".to_string(),
            body: Some(json::stringify(paths)),
            acl: Some("public-read".to_string()),
            ..Default::default()
        }).sync().expect("could not upload");
    }
    

    我得到的错误是

    error[E0308]: mismatched types
      --> src/main.rs:16:20
       |
    16 |         body: Some(json::stringify(paths)),
       |                    ^^^^^^^^^^^^^^^^^^^^^^ expected struct `rusoto_core::ByteStream`, found struct `std::string::String`
       |
       = note: expected type `rusoto_core::ByteStream`
                  found type `std::string::String`
    

    我不知道怎么给这个 ByteStream …… ByteStream::new(json::stringify(paths)) 不起作用,给了我一个不同的错误。

    如何上传字符串?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Shepmaster Tim Diekmann    6 年前

    StreamingBody 是类型别名:

    type StreamingBody = ByteStream;
    

    ByteStream 具有多个构造函数,包括 implementation of From :

    impl From<Vec<u8>> for ByteStream
    

    您可以转换 String 变成一个 Vec<u8> 使用 String::into_bytes . 一起:

    fn example(s: String) -> rusoto_s3::StreamingBody {
        s.into_bytes().into()
    }