Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading image in ASP.NET Boilerplate

When posting an image, HttpContext.Current.Request is null.

Is there any simple way to achieve this? I am using dropzone.js on client side.

Project is Angular with Web API (ASP.NET Core 2.0) template.

[HttpPost]      
public HttpResponseMessage UploadJsonFile()
{
    HttpResponseMessage response = new HttpResponseMessage();           
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
    }
    return response;
}
like image 632
Nighil Avatar asked Oct 21 '25 15:10

Nighil


1 Answers

This is the code which i had done it is working fine.

public void PostFile(IFormFile file)
{          
    var uploads = Path.Combine("ROOT PATH FOR THE FILES", "uploads");

    if (file.Length > 0)
    {
        var filePath = Path.Combine(uploads, file.FileName);

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
}
like image 56
Nighil Avatar answered Oct 23 '25 07:10

Nighil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!