An async parser for multipart/form-data
content-type in Rust.
It accepts a Stream
of Bytes
as
a source, so that It can be plugged into any async Rust environment e.g. any async server.
Add this to your Cargo.toml
:
toml
[dependencies]
multer = "2.0"
```rust use bytes::Bytes; use futures::stream::Stream; // Import multer types. use multer::Multipart; use std::convert::Infallible; use futures::stream::once;
async fn main() -> Result<(), Box
// Create a `Multipart` instance from that byte stream and the boundary.
let mut multipart = Multipart::new(stream, boundary);
// Iterate over the fields, use `next_field()` to get the next field.
while let Some(mut field) = multipart.next_field().await? {
// Get field name.
let name = field.name();
// Get the field's filename if provided in "Content-Disposition" header.
let file_name = field.file_name();
println!("Name: {:?}, File Name: {:?}", name, file_name);
// Process the field data chunks e.g. store them in a file.
while let Some(chunk) = field.chunk().await? {
// Do something with field chunk.
println!("Chunk: {:?}", chunk);
}
}
Ok(())
}
// Generate a byte stream and the boundary from somewhere e.g. server request body.
async fn getbytestreamfromsomewhere() -> (impl Stream
(stream, "X-BOUNDARY")
} ```
This crate also provides some APIs to prevent potential DoS attacks with fine grained control. It's recommended to add some constraints on field (specially text field) size to prevent DoS attacks exhausting the server's memory.
An example:
```rust use multer::{Multipart, Constraints, SizeLimit};
async fn main() -> Result<(), Boxmy_text_field
and my_file_field
fields,
// For any unknown field, we will throw an error.
.allowedfields(vec!["mytextfield", "myfilefield"])
.sizelimit(
SizeLimit::new()
// Set 15mb as size limit for the whole stream body.
.wholestream(15 * 1024 * 1024)
// Set 10mb as size limit for all fields.
.perfield(10 * 1024 * 1024)
// Set 30kb as size limit for our text field only.
.forfield("mytext_field", 30 * 1024),
);
// Create a `Multipart` instance from a stream and the constraints.
let mut multipart = Multipart::with_constraints(some_stream, "X-BOUNDARY", constraints);
while let Some(field) = multipart.next_field().await.unwrap() {
let content = field.text().await.unwrap();
assert_eq!(content, "abcd");
}
Ok(())
} ```
An example showing usage with hyper.rs.
For more examples, please visit examples.
Your PRs and suggestions are always welcome.