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; }
@Html.LabelFor(model => model.FileAttachment, htmlAttributes: new { @class = "col-md-4 col-form-label text-md-right" })
public async Task 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}");
}
Jaydeep PatilPosted May 11, 2024, 10:48 AM
Hi,
Check my below article for the same. It might be helpful to you. In that I mentioned how to upload single and multiple files.
https://www.c-sharpcorner.com/article/upload-single-and-multiple-files-using-the-net-core-6-web-api/
Thanks!
Jaimin ShethiyaPosted May 11, 2024, 10:13 AM
Hello,
Please refere below links.
https://stackoverflow.com/questions/67061125/upload-file-into-asp-net-core-web-api
https://andrewhalil.com/2021/06/23/how-to-implement-a-file-uploader-using-net-core-web-api/
https://stackoverflow.com/questions/35379309/how-to-upload-files-in-asp-net-core
Thanks
Vikas SinghPosted May 11, 2024, 8:57 AM
Your code seems mostly correct, but there are a few adjustments and corrections needed:
HTML Form:
forattribute of the label should match the id of the input element.enctype="multipart/form-data"in your form tag.Controller Action:
[HttpPost].Here's your corrected code:
HTML Form:
@model NCRCapturingForm
Controller Action:
[HttpPost] Upload(NCRCapturingForm model)
public async Task
{
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}");
}
Ensure your form is submitting to the correct action (
Upload), and that it is using thePOSTmethod. Also, ensure that theNCRCapturingFormmodel includes other properties you might have in your form, not just theFileAttachmentproperty.