Add Field::chunk (#901)

* Added chunk function to multipart field

This fixes not being able to stream data from a multipart directly into a file or other output.

* doc comment for clarification of usage and &mut self

* fixed formatting

* Corrected example to reflex best practices

* Removed unwrap

* clean up docs

* update changelog

Co-authored-by: David Pedersen <[email protected]>
This commit is contained in:
Tristan Bouchard
2022-04-04 09:26:11 +02:00
committed by GitHub
co-authored by David Pedersen
parent 3e716f303f
commit d417910a16
2 changed files with 49 additions and 1 deletions
+4 -1
View File
@@ -7,7 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# Unreleased
- None.
- **added:** Add `axum::extract::multipart::Field::chunk` method for streaming a single chunk from
the field ([#901])
[#901]: https://github.com/tokio-rs/axum/pull/901
# 0.5.1 (03. April, 2022)
+45
View File
@@ -142,6 +142,51 @@ impl<'a> Field<'a> {
pub async fn text(self) -> Result<String, MultipartError> {
self.inner.text().await.map_err(MultipartError::from_multer)
}
/// Stream a chunk of the field data.
///
/// When the field data has been exhausted, this will return [`None`].
///
/// Note this does the same thing as `Field`'s [`Stream`] implementation.
///
/// # Example
///
/// ```
/// use axum::{
/// extract::Multipart,
/// routing::post,
/// response::IntoResponse,
/// http::StatusCode,
/// Router,
/// };
///
/// async fn upload(mut multipart: Multipart) -> Result<(), (StatusCode, String)> {
/// while let Some(mut field) = multipart
/// .next_field()
/// .await
/// .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?
/// {
/// while let Some(chunk) = field
/// .chunk()
/// .await
/// .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?
/// {
/// println!("received {} bytes", chunk.len());
/// }
/// }
///
/// Ok(())
/// }
///
/// let app = Router::new().route("/upload", post(upload));
/// # let _: Router<axum::body::Body> = app;
/// ```
pub async fn chunk(&mut self) -> Result<Option<Bytes>, MultipartError> {
self.inner
.chunk()
.await
.map_err(MultipartError::from_multer)
}
}
/// Errors associated with parsing `multipart/form-data` requests.