I've been reading a lot of post and articles and still have no idea why my request fails. There is a asp net core 3.1 app. Simple controller code :
[Route("api/v1/user")]
public class BlobController : Controller
{
[HttpPost("uploadphoto")]
public async Task<UploadPhotoResponse> UploadPhoto([FromForm] IFormFile file)
{
return null;
}
}
Postman request :
Headers :
Every time i'm getting 400 bad request result and can't get inside UploadPhoto method.
CodePudding user response:
Change IFormFile
to UploadPhotoRequest
--> multipart file
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace UploadPhoto.Controllers
{
public class UploadPhotoRequest
{
public IFormFile File { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
}
[ApiController]
[Route("api/v1/user")]
public class WeatherForecastController : ControllerBase
{
[HttpPost("uploadphoto")]
public string UploadPhoto([FromForm] UploadPhotoRequest file)
{
Console.WriteLine(file.Name);
return file.Name;
}
}
}
Postman Collection to verify
{"auth":null,"event":null,"info":{"_postman_id":null,"description":null,"name":"test.http","schema":"https://schema.getpostman.com/json/collection/v2.1.0/collection.json","version":null},"item":[{"description":null,"event":null,"id":null,"name":"1","protocolProfileBehavior":null,"request":{"auth":null,"body":{"disabled":null,"file":null,"formdata":[{"contentType":"application/json","description":null,"disabled":null,"key":"image","type":"file","value":"settings.json","src":null},{"contentType":null,"description":null,"disabled":null,"key":"name","type":"text","value":"ram","src":null}],"graphql":null,"mode":"formdata","options":null,"raw":null,"urlencoded":null},"certificate":null,"description":"1","header":null,"method":"POST","proxy":null,"url":"https://localhost:5001/api/v1/user/uploadphoto"},"response":null,"variable":null,"auth":null,"item":null}],"protocolProfileBehavior":null,"variable":null}
There are two ways to upload files.
- Uploading via single file
- Uploading via multipart
This option is used, if there are multiple files/fields to upload
To upload single file, In postman
To Upload multipart file, In postman
- Switch to body tab
- select form-data
- add keys
if it is a file, hover to the right section of key. you will see option to change it to file.
Alternative solution
Dothttp is similar tool with great control over these.
For Single file
POST https://req.dothttp.dev
// select as a binary
fileinput('C:\Users\john\documents\photo.jpg') // path to file
For Multipart upload
POST https://req.dothttp.dev
// selects as multipart
multipart(
'name'< 'john',
'photo'< 'C:\Users\john\documents\photo.jpg',
// and many more
)