So I am trying to upload a file to the server. I am using postman to test the file upload, but I am getting the error "Invalid `boundary` for `multipart/form-data` request" in postman with the HTTP status code 400. Here is my code:
async fn main() {
let paths = Router::new()
.route("/upload", post(upload))
.layer(DefaultBodyLimit::disable())
.layer(RequestBodyLimitLayer::new(250 * 1024 * 1024));
let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, paths).await.unwrap();
}
async fn upload(mut files: Multipart) -> impl IntoResponse {
while let Some(field) = files.next_field().await.unwrap() {
let name = field.file_name().unwrap().to_string();
println!("{name}, {}", field.content_type().unwrap());
}
StatusCode::OK
}
In postman, the HTTP Request is a post request that contains form-data in the body. The key is fileupload
and the value is 2 files.
What does this error mean and how can I resolve it?
Edit: Here is what the Postman HTTP Request looks like:
POST /upload HTTP/1.1
Host: localhost:3000
Content-Length: 418
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="fileupload"; filename="1ef9fae3-1302-4760-849c-1b1a73c36d70"
Content-Type: <Content-Type header here>
(data)
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="fileupload"; filename="1ef9facc-6eae-4990-9203-292653b9662f"
Content-Type: <Content-Type header here>
(data)
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Looks like the problem may be related to Postman not being able to figure out what the Content-Type of each file is, since your filename has no extension.
Content-Type: <Content-Type header here>
should be filled with the file's content type: Content-Type: text/plain
.
Try either adding an extension to the filename to help Postman identify it, or go the the Body tab, click the "..." kebab button in the top-right corner of the table, and check the "Content-Type" column to reveal it. Then just explicitly define the content type of your files.