I was trying to upload a single image file. Sample code is as follows:
/// <summary>
/// Uploads a single image document
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("{id}/scan-doc-image")]
//[RequestFormLimits(ValueLengthLimit = int.MaxValue, MultipartBodyLengthLimit = int.MaxValue)]
public async Task<ActionResult> UploadImage(int id, IFormFile file)
{
// more validation goes here.
if (file == null)
{
return BadRequest();
}
// save image if any
if (file.Length > 0)
{
var uploads = Path.Combine(_envirnment.WebRootPath, "uploads");
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
return Ok();
}
Here is what I noticed:
Making a call to this API automatically STOPS the service. I tried many many times and it always shuts it down. It didn't stop the service when I make other API calls. Just FYI
I tried making a call from POSTMAN as well. This time, it didn't close the service but I keep getting errors:
Failed to read the request form. Missing content-type boundary.Note that, I am specifing Content-Type asmultipart/form-data. And when I specify the boundary a number less than max, it still errors. Even when I uncomment theRequestFormLimitattribute you see above, it didn't help either.
So what I am missing here? All I need it to upload a single image file.
Content-Typeheader manually. You are overriding the value set by Postman. Just selectform-datain POST request and send your request to see if it works. No need to setheaderwhenform-datais posted. Just remove theContent-Typeand upload as below.Note for the path which may causes error
If you are using Web API project, you will get null in
_envirnment.WebRootPath. There is nowwwwdirectory in Web API project.Solution
Change
WebRootPathto
ContentRootPathTest
Codes of controller
If the specified folder "uploads" does not exist, create it firstly , and then save file to this folder. If the folder already exists, just save the file in it.