For hyper 1.x, is there any example to upload a file with PUT method in a streaming way? #3853
-
I am using hyper v1.6, try googling and coding a lot but just could not find how to do it. it's very hard use http_body_util::{BodyExt, Empty, StreamBody};
use hyper::{
Request,
body::{Body, Bytes, Frame},
};
use hyper_util::rt::TokioIo;
use tokio::net::TcpStream;
use tokio::{fs::File, io::BufReader};
use tokio_util::codec::{BytesCodec, FramedRead};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("Hello, world!");
let stream = TcpStream::connect("http://www.google.com").await.unwrap();
let io = TokioIo::new(stream);
let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await?;
let url: hyper::Uri = "https://www.google.com".parse().unwrap();
// read a file as a stream and send it
let file = File::open("/path/to/your/file").await?;
// create a stream from the file
// Get file size for Content-Length header
let file_size = file.metadata().await?.len();
// Convert file into a stream of Bytes ???
let file_stream = FramedRead::new(file, BytesCodec::new());
// Wrap the stream into a Hyper Body
// let body = ???
let req = Request::builder()
.uri(&url)
.method("PUT")
.header(hyper::header::HOST, url.authority().unwrap().as_str())
.body(body)
.unwrap();
let x = sender.send_request(req).await.unwrap();
Ok(())
} If you know how to code this, please help, thank you! |
Beta Was this translation helpful? Give feedback.
Answered by
seanmonstar
Mar 5, 2025
Replies: 1 comment 1 reply
-
You could look at the very similar send_file server example, adapting it to be used with a client. Another alternative, if you don't specifically need to the control at hyper's level, is to just use reqwest. It makes this stuff easy for you. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
zjhken
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could look at the very similar send_file server example, adapting it to be used with a client.
Another alternative, if you don't specifically need to the control at hyper's level, is to just use reqwest. It makes this stuff easy for you.