imgurs/src/imgur/requests/upload_image.rs

37 lines
1.0 KiB
Rust
Raw Normal View History

2022-06-12 15:28:25 +00:00
use std::collections::HashMap;
2022-01-22 21:02:51 +00:00
use reqwest::Method;
2022-01-22 21:02:51 +00:00
2022-06-12 15:41:50 +00:00
use crate::{api_url, send_api_request, Error, ImageInfo, ImgurClient, Result};
2022-01-22 21:02:51 +00:00
2022-06-12 15:28:25 +00:00
pub async fn upload_image(client: &ImgurClient, image: String) -> Result<ImageInfo> {
// create http form (hashmap)
let mut form = HashMap::new();
// insert image to form
form.insert("image", image);
2022-01-22 21:02:51 +00:00
// get imgur api url
let uri = api_url!("image");
// send request to imgur api
2022-04-03 19:11:11 +00:00
let res = send_api_request(client, Method::POST, uri, Some(form)).await?;
2022-01-22 21:02:51 +00:00
// get response http code
2022-01-22 21:02:51 +00:00
let status = res.status();
// check if an error has occurred
2022-01-22 21:02:51 +00:00
if status.is_client_error() || status.is_server_error() {
2022-06-12 15:28:25 +00:00
let body = res.text().await?;
2022-06-12 15:28:25 +00:00
// if body is too long do not return it (imgur sometimes returns whole Request)
if body.chars().count() > 50 {
Err(Error::ApiErrorBodyTooLong(status.as_u16()))?;
}
2022-06-12 15:28:25 +00:00
return Err(Error::ApiError(status.as_u16(), body));
2022-01-22 21:02:51 +00:00
}
2022-06-12 15:28:25 +00:00
// return `ImageInfo`
Ok(res.json().await?)
2022-01-22 21:02:51 +00:00
}