append original file name to urls

This commit is contained in:
neri 2020-08-03 02:42:27 +02:00
parent b0b03f32a4
commit 64c2567918
2 changed files with 24 additions and 10 deletions

View File

@ -1,6 +1,6 @@
use std::{fmt::Display, str::FromStr};
#[derive(Debug)]
#[derive(Debug, PartialEq)]
pub(crate) enum FileKind {
TEXT,
BINARY,

View File

@ -58,7 +58,7 @@ async fn upload(
sqlx::query("INSERT INTO Files (file_id, file_name, valid_till, kind) VALUES ($1, $2, $3, $4)")
.bind(&file_id)
.bind(original_name.unwrap_or_else(|| file_id.clone()))
.bind(original_name.as_ref().unwrap_or_else(|| &file_id))
.bind(valid_till.naive_local())
.bind(kind.to_string())
.execute(db.as_ref())
@ -74,13 +74,25 @@ async fn upload(
sender.send(()).await;
let redirect = if kind == FileKind::BINARY && original_name.is_some() {
format!("/upload/{}/{}", file_id, original_name.unwrap())
} else {
format!("/upload/{}", file_id)
};
Ok(HttpResponse::SeeOther()
.header("location", format!("/upload/{}", file_id))
.header("location", redirect)
.finish())
}
async fn uploaded(id: web::Path<String>, req: web::HttpRequest) -> Result<HttpResponse, Error> {
let url = req.url_for("file", &[id.as_str()])?;
async fn uploaded(req: web::HttpRequest) -> Result<HttpResponse, Error> {
let id = req.match_info().query("id");
let name = req.match_info().get("name");
let conn = req.connection_info();
let url = if let Some(name) = name {
format!("{}://{}/file/{}/{}", conn.scheme(), conn.host(), id, name)
} else {
format!("{}://{}/file/{}", conn.scheme(), conn.host(), id)
};
let upload_html = UPLOAD_HTML.replace("{url}", url.as_str());
Ok(HttpResponse::Ok()
.content_type("text/html")
@ -89,12 +101,12 @@ async fn uploaded(id: web::Path<String>, req: web::HttpRequest) -> Result<HttpRe
async fn download(
req: HttpRequest,
id: web::Path<String>,
db: web::Data<PgPool>,
config: web::Data<Config>,
) -> Result<HttpResponse, Error> {
let id = req.match_info().query("id");
let mut cursor = sqlx::query("SELECT file_id, file_name, kind from files WHERE file_id = $1")
.bind(id.as_ref())
.bind(id)
.fetch(db.as_ref());
let row: PgRow = cursor
.next()
@ -218,10 +230,12 @@ async fn main() -> std::io::Result<()> {
.data(config.clone())
.service(web::resource("/").route(web::get().to(index)))
.service(web::resource("/upload").route(web::post().to(upload)))
.service(web::resource("/upload/{id}").route(web::get().to(uploaded)))
.service(
web::resource("/file/{id}")
.name("file")
web::resource(["/upload/{id}", "/upload/{id}/{name}"])
.route(web::get().to(uploaded)),
)
.service(
web::resource(["/file/{id}", "/file/{id}/{name}"])
.route(web::get().to(download)),
)
.service(Files::new("/static", "static").disable_content_disposition())