Skip to content

Commit

Permalink
feat: add AsyncSeek trait to Upload::into_async_read return type (#853)
Browse files Browse the repository at this point in the history
Co-authored-by: chen.fengyuan <[email protected]>
  • Loading branch information
chenfengyuan and chen.fengyuan authored Jul 27, 2024
1 parent b22a58a commit b60d803
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions poem-openapi/src/types/multipart/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
use poem::web::Field as PoemField;
use tokio::{
fs::File,
io::{AsyncRead, AsyncReadExt, Error as IoError, ErrorKind},
io::{AsyncRead, AsyncReadExt, AsyncSeek, Error as IoError, ErrorKind},
};

use crate::{
Expand Down Expand Up @@ -74,7 +74,7 @@ impl Upload {
}

/// Consumes this body object to return a reader.
pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + 'static {
pub fn into_async_read(self) -> impl AsyncRead + AsyncSeek + Unpin + Send + 'static {
self.file
}

Expand Down
29 changes: 29 additions & 0 deletions poem-openapi/tests/multipart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use poem_openapi::{
},
Enum, Multipart, Object,
};
use tokio::io::{AsyncReadExt, AsyncSeekExt};

fn create_multipart_payload(parts: &[(&str, Option<&str>, &[u8])]) -> Vec<u8> {
let mut data = Vec::new();
Expand Down Expand Up @@ -237,6 +238,34 @@ async fn upload() {
assert_eq!(a.file.content_type(), None);
assert_eq!(a.file.size(), 3);
assert_eq!(a.file.into_vec().await.unwrap(), vec![1, 2, 3]);

let data =
create_multipart_payload(&[("name", None, b"abc"), ("file", Some("1.txt"), &[1, 2, 3])]);
let a = A::from_request(
&Request::builder()
.header("content-type", "multipart/form-data; boundary=X-BOUNDARY")
.finish(),
&mut RequestBody::new(data.into()),
)
.await
.unwrap();
assert_eq!(a.name, "abc".to_string());

assert_eq!(a.file.file_name(), Some("1.txt"));
assert_eq!(a.file.content_type(), None);
assert_eq!(a.file.size(), 3);

let mut reader = a.file.into_async_read();
let mut buffer = [0; 3];
let n = reader.read_exact(&mut buffer[..]).await.unwrap();
assert_eq!(n, 3);
assert_eq!(buffer[..n], vec![1, 2, 3]);
let n = reader.read(&mut buffer[..]).await.unwrap();
assert_eq!(n, 0); // EOF
reader.seek(std::io::SeekFrom::Start(0)).await.unwrap();
let n = reader.read_exact(&mut buffer[..]).await.unwrap();
assert_eq!(n, 3);
assert_eq!(buffer[..n], vec![1, 2, 3]);
}

#[tokio::test]
Expand Down

0 comments on commit b60d803

Please sign in to comment.