Web API uploading a file to a folder
Good time of day! What is there: an API controller with a method that accepts a file that I upload via Postman to form-data and attach the file. Problem: the controller fails, but there is no file. I tried to write in the parameters of the IFormFile method, but in this case, the method does not get at all and returns a void. My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Impulse_Back_end.Models;
using Impulse_Back_end.Data;
using System.IO;
using System.Net.Http.Headers;
using Impulse_Back_end.Core.Interfaces;
namespace Impulse_Back_end.Controllers {
[ApiController, Route("api/data/upload")]
public class FileUploadController : Controller {
ApplicationDbContext db;
public FileUploadController(ApplicationDbContext _context) {
db = _context;
}
[HttpPost, DisableRequestSizeLimit, Route("file")]
public IActionResult Upload() {
try {
var file = Request.Form.Files[0];
var folderName = Path.Combine("wwwroot", "images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0) {
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create)) {
file.CopyTo(stream);
}
return Ok(new { dbPath });
}
else {
return BadRequest();
}
}
catch (Exception ex) {
return StatusCode(500, $"Internal server error: {ex}");
}
}
}
}
1 answers
Example of the simplest method of loading without checks and other things
[HttpPost, DisableRequestSizeLimit, Route("file")]
public IActionResult Post(IFormFile file)
{
using(var fstream = new FileInfo(file.FileName).Create())
{
file.CopyTo(fstream);
return Ok();
}
}
And now follow the hands in Postman:
The name of the IFormFile parameter (in the example - file
) and the value of the KEY field for the record with the uploaded file (circled in the picture) must match, if these values differ, you will get null in the controller instead of the stream of the uploaded file.
I would like to add that I prefer to use Swagger for manual testing, it is somewhat more convenient, because it generates correct requests independently, based on the parameters of your controllers.