Answer the question
In order to leave comments, you need to log in
How to download a file from a direct link?
Hello. I've been learning Rust for about a week, because I'm pretty fed up with Python alone. Decided to discover something new. So, I looked at the basics themselves, it seems to be nothing unusual, but then I wanted to do what I did in Python. Namely, from the very beginning, I always tried to do something quite complicated. And so I got to downloading the file.
In fact, downloading a file is, after all, receiving bytes? And if in Python this can be done with a request using one library, after which everything can be written to a file, then in Rust it is possible. So right?
I looked at tutorials and examples on this topic, but I didn’t really understand anything. First the main() function cannot be asynchronous, then Result is a type that represents either success (Ok) or failure (Err). Tried to get data with reqwest::get() and hyper, but there was always a problem with async and writing data (which I couldn't get) to a file.
Even if everything seems to be normal, something will still go wrong.
485 | pub enum Result<T, E> {
| ^^^^^^ - -
help: add missing generic argument
|
6 | async fn main() -> Result<(), E> {
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let target = "https://www.rust-lang.org/static/images/rust-logo-blk.svg";
let response = reqwest::get(target).await?;
let path = Path::new("C:/Users/polzo/Desktop/image.svg");
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}", why),
Ok(file) => file,
};
let content = response.text().await?;
file.write_all(content.as_bytes())?;
Ok(())
}
Answer the question
In order to leave comments, you need to log in
Xs what exactly was wrong (I suspect 'add missing generic argument')
But this works:
use std::{fs::OpenOptions, io::Write, path::Path};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let target = "https://www.rust-lang.org/static/images/rust-logo-blk.svg";
let response = reqwest::get(target).await?;
let path = Path::new("./image.svg");
let mut file = OpenOptions::new().create(true).write(true).open(path)?;
let content = response.text().await?;
file.write_all(content.as_bytes())?; // Хочу асинхронно писать в файлы. Как это можно сделать?
Ok(())
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question