Downloading images

Let's implement a branch to download images. The handler can download files using the  /download/filename path. To extract the name of the file, we use a regular expression:

lazy_static! {
static ref DOWNLOAD_FILE: Regex = Regex::new("^/download/(?P<filename>\w{20})?$").unwrap();
}

We will use startwith to detect the /download part of the path. Take a look at the implementation:

(&Method::GET, path) if path.starts_with("/download") => {
if let Some(cap) = DOWNLOAD_FILE.captures(path) {
let filename = cap.name("filename").unwrap().as_str();
let mut filepath = files.to_path_buf();
filepath.push(filename);
let open_file = File::open(filepath);
let body = open_file.map(|file| {
let chunks = FileChunkStream::new(file);
Response::new(Body::wrap_stream(chunks))
});
Box::new(body)
} else {
response_with_code(StatusCode::NOT_FOUND)
}
}

In this example, we expect a GET method and check that the paths match with the DOWNLOAD_FILE regular expression. We use the name "filename" to extract a string with the name of the file. Since we have the filepath variable with a path to a folder, we convert the Path value to the PathBuf  type using the to_path_buf method of the Path instance and push a filename to it. After that, we use the file type of the tokio crate to open a file, which has asynchronous reading and writing capabilities to work with the file's content. The open method of the file returns an OpenFuture instance that resolves to a File instance when it is successful.

We wrap a file with FileChunkStream, imported from the hyper_staticfile crate. This stream reads a File and returns chunks of bytes. The body has a wrap_stream method and we can send the whole stream as a response. When the stream is forwarded to a client, the opened File will be closed when the stream is dropped. 

The last thing we should do is return a Body instance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.205.136