diff --git a/.changes/upload-returnval.md b/.changes/upload-returnval.md new file mode 100644 index 000000000..30768d48b --- /dev/null +++ b/.changes/upload-returnval.md @@ -0,0 +1,6 @@ +--- +"upload": patch +"upload-js": patch +--- + +Return the upload response as a string and error out if the status code is not within 200-299. diff --git a/plugins/upload/guest-js/index.ts b/plugins/upload/guest-js/index.ts index 08620f02c..619b0679f 100644 --- a/plugins/upload/guest-js/index.ts +++ b/plugins/upload/guest-js/index.ts @@ -33,7 +33,7 @@ async function upload( filePath: string, progressHandler?: ProgressHandler, headers?: Map, -): Promise { +): Promise { const ids = new Uint32Array(1); window.crypto.getRandomValues(ids); const id = ids[0]; @@ -44,7 +44,7 @@ async function upload( await listenToEventIfNeeded("upload://progress"); - await invoke("plugin:upload|upload", { + return await invoke("plugin:upload|upload", { id, url, filePath, diff --git a/plugins/upload/src/lib.rs b/plugins/upload/src/lib.rs index 9d9966da2..d0336f782 100644 --- a/plugins/upload/src/lib.rs +++ b/plugins/upload/src/lib.rs @@ -29,6 +29,8 @@ pub enum Error { Request(#[from] reqwest::Error), #[error("{0}")] ContentLength(String), + #[error("request failed with status code {0}: {1}")] + HttpErrorCode(u16, String), } impl Serialize for Error { @@ -93,13 +95,17 @@ async fn upload( url: &str, file_path: &str, headers: HashMap, -) -> Result { +) -> Result { // Read the file let file = File::open(file_path).await?; + let file_len = file.metadata().await.unwrap().len(); // Create the request and attach the file to the body let client = reqwest::Client::new(); - let mut request = client.post(url).body(file_to_body(id, window, file)); + let mut request = client + .post(url) + .header(reqwest::header::CONTENT_LENGTH, file_len) + .body(file_to_body(id, window, file)); // Loop trought the headers keys and values // and add them to the request object. @@ -108,8 +114,14 @@ async fn upload( } let response = request.send().await?; - - response.json().await.map_err(Into::into) + if response.status().is_success() { + response.text().await.map_err(Into::into) + } else { + Err(Error::HttpErrorCode( + response.status().as_u16(), + response.text().await.unwrap_or_default(), + )) + } } fn file_to_body(id: u32, window: Window, file: File) -> reqwest::Body {