Guest User

Guest User

  • Tech Writer
  • 2.1k
  • 481.7k

How to upload file document in asp.net core using c#

May 11 2024 7:21 AM

Hi Team

I have an issue with my file upload and its not attaching the file when browser and attach it and when inspecting on the browser i dont see any js errors. What could be possible reason? When debugging its not hitting the method?


//model
[Display(Name = "File Attachment")]
 public IFormFile FileAttachment { get; set; }

<!-- File attachments -->
                    <div class="form-group row">
                        @Html.LabelFor(model => model.FileAttachment, htmlAttributes: new { @class = "col-md-4 col-form-label text-md-right" })
                        <div class="col-md-8">
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="file" name="FileAttachment">
                                <label class="custom-file-label" for="fileAttachment">Choose file</label>
                            </div>
                        </div>
                    </div>


            
        public async Task<IActionResult> Upload(NCRCapturingForm model)
        {
            if(model == null || model.FileAttachment == null || model.FileAttachment.Length == 0)
            {
                return BadRequest("No file uploaded");
            }
            var filePath = Path.GetTempFileName();
            using(var stream = new FileStream(filePath, FileMode.Create))
            {
                await model.FileAttachment.CopyToAsync(stream);
            }
            return Ok("$ File uploaded successfully. Path:{filePath}");
        }

 


Answers (3)