1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2025-06-20 16:35:17 +00:00

Handle multipart requests

This commit is contained in:
2020-06-20 11:37:29 +02:00
parent bab1fe8272
commit 25a368fd98
4 changed files with 50 additions and 21 deletions

View File

@ -3,8 +3,9 @@ use std::pin::Pin;
use actix_web::{App, FromRequest, http, HttpMessage, HttpRequest, HttpResponse, HttpServer, web};
use actix_web::dev::{Decompress, Payload, PayloadStream};
use actix_web::error::{ErrorBadRequest, PayloadError};
use actix_web::error::{ErrorBadRequest, ErrorInternalServerError, PayloadError};
use actix_web::web::{Bytes, BytesMut};
use bytes::{Buf, BufMut};
use encoding_rs::UTF_8;
use futures::{FutureExt, Stream, StreamExt};
use futures::future::LocalBoxFuture;
@ -133,18 +134,51 @@ impl FromRequest for CustomRequest {
// Add the value to the body
body_args.insert(
percent_decode_str(args[0]).decode_utf8_lossy().to_string(),
RequestValue::string(percent_decode_str(args[1]).decode_utf8_lossy().to_string()),
RequestValue::String(percent_decode_str(args[1]).decode_utf8_lossy().to_string()),
);
}
}
}
// Process "multipart/form-data" request
else if req.content_type().starts_with("multipart/form-data") {
let mut req = actix_multipart::Multipart::new(req.headers(), payload);
// Process the list of arguments
while let Some(el) = req.next().await {
let mut field = el?;
let content_type = field.content_disposition().ok_or(
ErrorInternalServerError("F1"))?;
let name = content_type.get_name().ok_or(
ErrorInternalServerError("Missing field name!"))?;
// Handle file upload
if content_type.get_filename().is_some() && name.eq("file") {
let filename = content_type.get_filename().unwrap();
let mut buf = BytesMut::new();
while let Some(chunk) = field.next().await {
let data = chunk.unwrap();
buf.put(data);
}
body_args.insert(name.to_string(),
RequestValue::File(filename.to_string(), buf.to_bytes()));
}
// It is a simple field
else {
let mut content = String::new();
// Get content
while let Some(chunk) = field.next().await {
content = format!("{}{}", content, String::from_utf8_lossy(chunk?.bytes()));
}
body_args.insert(name.to_string(), RequestValue::String(content));
}
}
}