Skip to main content

playwright_rs/protocol/
file_payload.rs

1// FilePayload protocol type
2//
3// Represents a file to be uploaded with explicit name, MIME type, and buffer.
4//
5// See: https://playwright.dev/docs/api/class-locator#locator-set-input-files
6
7/// FilePayload represents a file for advanced file uploads.
8///
9/// Allows explicit control over filename, MIME type, and file contents
10/// when uploading files to input elements.
11///
12/// # Example
13///
14/// ```no_run
15/// # use playwright_rs::protocol::FilePayload;
16/// let file = FilePayload::new("document.pdf", "application/pdf", vec![/* PDF bytes */]);
17/// ```
18///
19/// See: <https://playwright.dev/docs/api/class-locator#locator-set-input-files>
20#[derive(Debug, Clone)]
21#[non_exhaustive]
22pub struct FilePayload {
23    /// File name
24    pub name: String,
25    /// MIME type
26    pub mime_type: String,
27    /// File contents as bytes
28    pub buffer: Vec<u8>,
29}
30
31use crate::error::Result;
32use std::fs;
33use std::path::Path;
34
35impl FilePayload {
36    /// Creates a FilePayload from a name, MIME type, and contents.
37    pub fn new(name: impl Into<String>, mime_type: impl Into<String>, buffer: Vec<u8>) -> Self {
38        Self {
39            name: name.into(),
40            mime_type: mime_type.into(),
41            buffer,
42        }
43    }
44
45    /// Creates a FilePayload from a file path.
46    ///
47    /// Automatically detects the MIME type based on the file extension.
48    /// Reads the file into memory.
49    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
50        let path = path.as_ref();
51        let name = path
52            .file_name()
53            .ok_or_else(|| crate::Error::InvalidPath(format!("Path {:?} has no filename", path)))?
54            .to_string_lossy()
55            .into_owned();
56
57        let mime_type = crate::protocol::mime::from_path(path).to_string();
58        let buffer = fs::read(path)?;
59
60        Ok(Self {
61            name,
62            mime_type,
63            buffer,
64        })
65    }
66
67    /// Creates a FilePayload from a file path with an explicit MIME type.
68    pub fn from_file<P: AsRef<Path>>(path: P, mime_type: &str) -> Result<Self> {
69        let path = path.as_ref();
70        let name = path
71            .file_name()
72            .ok_or_else(|| crate::Error::InvalidPath(format!("Path {:?} has no filename", path)))?
73            .to_string_lossy()
74            .into_owned();
75
76        let buffer = fs::read(path)?;
77
78        Ok(Self {
79            name,
80            mime_type: mime_type.to_string(),
81            buffer,
82        })
83    }
84}