Created
February 25, 2024 15:57
-
-
Save plainionist/f9555173e94483ce65cf1daaf291d28e to your computer and use it in GitHub Desktop.
Observes a folder and uploads all files if anything changes in that folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher}; | |
use reqwest::blocking::{multipart, Client}; | |
use std::fs; | |
use std::path::Path; | |
fn main() { | |
let path = std::env::args().nth(1).expect("Argument 1 needs to be a path"); | |
println!("Watching {path}"); | |
watch(path); | |
} | |
fn watch<P: AsRef<Path>>(path: P) { | |
let (tx, rx) = std::sync::mpsc::channel(); | |
let mut watcher = RecommendedWatcher::new(tx, Config::default()).unwrap(); | |
watcher.watch(path.as_ref(), RecursiveMode::Recursive).unwrap(); | |
for res in rx { | |
match res { | |
Ok(event) => { | |
println!("Change: {event:?}"); | |
upload_folder(path.as_ref()) | |
} | |
Err(error) => println!("Error: {error:?}"), | |
} | |
} | |
} | |
fn upload_folder(path: &std::path::Path) { | |
for entry in fs::read_dir(path).unwrap() { | |
let path = entry.unwrap().path(); | |
if path.is_file() { | |
upload_file(&path); | |
} | |
} | |
} | |
fn upload_file(path: &std::path::Path) { | |
println!(" Uploading {}", path.display()); | |
let file_fs = fs::read(path).unwrap(); | |
let fname = path.file_name().unwrap().to_os_string().into_string().ok().unwrap(); | |
let part = multipart::Part::bytes(file_fs).file_name("filename.filetype"); | |
let form = multipart::Form::new() | |
.text("resourceName", "filename.filetype") | |
.part(fname, part); | |
let client = Client::new(); | |
let resp = client | |
.post("http://localhost:5236/upload") | |
.multipart(form) | |
.send() | |
.unwrap(); | |
println!(" => Status: {}", resp.status()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment