gpt4 book ai didi

rust - Rust:如何对大文件进行HTTP PUT?

转载 作者:行者123 更新时间:2023-12-03 11:35:59 25 4
gpt4 key购买 nike

在rust中,我正在使用ureq进行HTTP请求。这是一个有效的HEAD请求:

let resp = ureq::head(&url).timeout_connect(5_000).call();
if !resp.ok() {
return false;
}

我看到ureq supports是动词PUT,但 pub fn put(path: &str) -> Request并不完全确定如何使用它。如何将文件/文件句柄/完整路径传递给它?

这是我在bash中执行的操作:
$ curl -v http://192.168.1.100:9193/  -T deleteme.mp4
* Expire in 0 ms for 6 (transfer 0x1102880)
* Trying 192.168.1.100...
* TCP_NODELAY set
* Expire in 200 ms for 4 (transfer 0x1102880)
* Connected to 192.168.1.100 (192.168.1.100) port 9193 (#0)
> PUT /deleteme.mp4 HTTP/1.1
> Host: 192.168.1.100:9193
> User-Agent: curl/7.64.0
> Accept: */*
> Content-Length: 779189
> Expect: 100-continue
>
* Expire in 1000 ms for 0 (transfer 0x1102880)
< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 200 OK
< Date: Fri, 03 Jan 2020 23:57:41 GMT
< Content-Length: 0
<
* Connection #0 to host 192.168.1.100 left intact

$ curl -I http://192.168.1.100:9193/deleteme.mp4
HTTP/1.1 200 OK
Content-Length: 779189
Date: Fri, 03 Jan 2020 23:57:44 GMT

编辑1

由于文件很大,因此我无法将其全部读取到内存中(耗尽),因此我需要在两者之间使用bufio reader。下面是我尝试的代码,除了失败很短。在接收器上创建一个空文件。
Response[status: 500, status_text: Network Error] PUT deleteme.mp4 wrote: 0 bytes, took: 70.4µs
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};

const FILE_NAME: &str = "/tmp/deleteme.mp4";

fn main() -> Result<(), Box<dyn Error>> {
println!("Hello, world!");
let f = File::open(FILE_NAME)?;
let mut buffered_reader = BufReader::new(f);
let r = ureq::put("http://192.168.1.100:9193/deleteme.mp4").send(buffered_reader);
println!("{:?}", r);

println!("Bye!");

Ok(())
}

如何使 BufReaderureq之间的管道工作?

最佳答案

对于带有非空正文的HTTP请求,您必须设置Content-LengthTransfer-Encoding header 。例如,您的curl session 中有一个Content-Length header 。

ureq::Request::send_bytes ureq::Request::send_string 将为您设置此 header ,但 ureq::Request::send 不会。您必须自己做:

use std::error::Error;
use std::fs::File;
use std::io::BufReader;

fn main() -> Result<(), Box<dyn Error>> {
let f = File::open("/tmp/deleteme.mp4")?;
let metadata = f.metadata()?;
let buffered_reader = BufReader::new(f);
let r = ureq::put("http://192.168.1.100:9193/deleteme.mp4")
.set("Content-Length", &metadata.len().to_string())
.send(buffered_reader);
println!("{:?}", r);

Ok(())
}

关于rust - Rust:如何对大文件进行HTTP PUT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com