Topic: web api how to use Request.Files
below is the piece of code for referrence developed in .net framework api but, the same code is not working in .net core api projects. especially Request.Files since, in .net core there is no such a propery called Request.Files. From google some people said to include
Microsoft.AspNetCore.App but, then also its not working. Could you please suggest a work around wtih sample code?
[HttpPost] public HttpResponseMessage UploadFile() { foreach (string file in Request.Files) { var FileDataContent = Request.Files[file]; if (FileDataContent != null && FileDataContent.ContentLength > 0) { // take the input stream, and save it to a temp folder using the original file.part name posted var stream = FileDataContent.InputStream; var fileName = Path.GetFileName(FileDataContent.FileName); var UploadPath = Server.MapPath("~/App_Data/uploads"); Directory.CreateDirectory(UploadPath); string path = Path.Combine(UploadPath, fileName); try { if (System.IO.File.Exists(path)) System.IO.File.Delete(path); using (var fileStream = System.IO.File.Create(path)) { stream.CopyTo(fileStream); } // Once the file part is saved, see if we have enough to merge it Shared.Utils UT = new Shared.Utils(); UT.MergeFile(path); } catch (IOException ex) { // handle } } } return new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent("File uploaded.") }; }
Author: TEJA
PARTH
Please refer to the below code -
PostFile(IFormFile postedFile)
Controller / Action Method of ASP.NET Core Web API:
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace WebAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class FileUpDownloadController : ControllerBase
{
// Required to obtain physical path
private readonly IWebHostEnvironment _hostingEnvironment;
public FileUpDownloadController(IWebHostEnvironment hostingEnvironment)
{
this._hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async Task
{
string result = "";
if (postedFile != null && postedFile.Length > 0)
{
// Obtain file name of uploaded file
string filename = Path.GetFileName(postedFile.FileName);
// Physical path of application root
string contentRootPath = _hostingEnvironment.ContentRootPath;
string filePath = contentRootPath + "\\" +
"UploadedFiles\\" + filename;
using (var stream = new FileStream(filePath, FileMode.Create))
{
await postedFile.CopyToAsync(stream);
}
result = filename + " (" + postedFile.ContentType +
") - " + postedFile.Length +
" bytes upload complete";
}
else
{
result = "file upload fail";
}
return Content(result);
}
}
}
View used to upload file:
@{
ViewData["Title"] = "Upload";
}
Upload