0

I want to upload image to the image folder, but it will show this error. fronted is Angular 7.

Asp.Net Core MVC

CustomerRepo.cs

 public bool AddCustomer(ExpressWebApi.Models.CustomerModel customer)
 { 
   SqlConnection con =new SqlConnection();
   con.ConnectionString="Data Source=.;Initial Catalog=BLAbLADB;Persist Security Info=True;User ID=sa;Password=sasasa"; 

   SqlCommand cmd = new SqlCommand();
   cmd.Connection=con;

    //file upload start-----------------------
      string imageName = null;
      var httpRequest = HttpContext.Current.Request; 
      //upload the image
      var postedFile = httpRequest.Files["cusImage"];
      //Current custome filename
      imageName = new string(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
                imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
                var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
                postedFile.SaveAs(filePath); 
  //file upload end-------------------------


  cmd.CommandText=$@"INSERT INTO Customer ([CusName], [CusPassword], [CusEmail], [CusDob], [CusImage]) VALUES ('{customer.CusName}', '{customer.CusPassword}', '{customer.CusEmail}', '{customer.CusDob}','{imageName}');";

  cmd.Connection.Open();
  cmd.ExecuteNonQuery();
  cmd.Connection.Close();

  return true;
 }

register.html - in Angular Application

   var customerData = { 
     "cusName": form.value.userName,
     "cusPassword": form.value.password,
     "cusEmail": form.value.email,
     "cusDob": form.value.dob,
     "cusImage" : this.fileToUpload
   };

 //for photo upload start---------------------------------
 handleFileInput(file:FileList){
 this.fileToUpload=file.item(0);

//show image preview
var reader = new FileReader();
reader.onload=(event:any)=>{
  this.imageUrl=event.target.result;
}
reader.readAsDataURL(this.fileToUpload);
}
//for photo upload end---------------------------------

Error CS0117 'HttpContext' does not contain a definition for 'Current'

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
Thevin Malaka.
  • 151
  • 1
  • 7
  • 20
  • 2
    In Asp.Net Core `HttpContext` no longer has that static property. – Nkosi Apr 20 '19 at 18:19
  • This might be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Provide a [mcve] that clarifies your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – Nkosi Apr 20 '19 at 18:19
  • What/Where is invoking `AddCustomer`? – Nkosi Apr 20 '19 at 18:32

1 Answers1

1

In .NET Core the context is part of the controller class as an HttpContext property. and the Request is available as HttpContext.Request and from there you can access the forms data.

However, in Core the syntax for file uploads has changed so the code you have above is not going to work without some changes. In your case you're using Model binding and you need to set up your Request model to handle the incoming file(s).

The following is from the Http Upload document on the ASP.NET Core docs:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

You can use this same interface for individual files in a model, or individual files passed [FromBody] as parameters.

In your case your incoming model should have a property like this:

public IFormFile cusImage {get; set;}

to capture the inbound file.

Rick Strahl
  • 17,302
  • 14
  • 89
  • 134