I am trying to upload a file using htmx using .NET Core. I have the following files in an ASP.NET Core MVC project that uses htmx.
Controller:
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using MyMvcProject.Models;
namespace MyMvcProject.Controllers;
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Upload(IFormFile fileToUpload)
{
if (fileToUpload == null || fileToUpload.Length == 0)
{
return Content("Please select a file to upload.");
}
// Save the file to a desired location (adjust the path as needed)
string filePath = Path.Combine("Uploads", fileToUpload.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
fileToUpload.CopyTo(stream);
}
return Content($"File uploaded successfully: {fileToUpload.FileName}");
}
}
And this is the view:
<html>
<head>
<title>File Upload with HTMX</title>
</head>
<body>
<form hx-post="/Home/Upload" hx-target="#upload-result" hx-encoding="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<button type="submit">Upload</button>
</form>
<div id="upload-result"></div>
</body>
</html>
For some reason, when I select a file to upload and click the "Upload" button, fileToUpload
variable in the Upload
action method is always null.
Does anyone know what I'm doing wrong please? Because it's not obvious to me... In other words, when I click the button, I always get the message
Please select a file to upload
in the browser.
Thanks
For some reason, when I select a file to upload and click the "Upload" button, fileToUpload variable in the Upload action method is always null.
Does anyone know what I'm doing wrong please?
The issue relates that you didn't add the Htmx JS script reference. Try to add the Htmx JS script in the head, like this:
@{
ViewData["Title"] = "HtmxIndex";
Layout = null;
}
<html>
<head>
<title>File Upload with HTMX</title>
@* <script src="https://unpkg.com/htmx.org@2.0.3" integrity="sha384-0895/pl2MU10Hqc6jd4RvrthNlDiE9U1tWmX7WRESftEDRosgxNsQG/Ze9YMRzHq" crossorigin="anonymous"></script> *@
<script src="https://unpkg.com/htmx.org@2.0.3/dist/htmx.js" integrity="sha384-BBDmZzVt6vjz5YbQqZPtFZW82o8QotoM7RUp5xOxV3nSJ8u2pSdtzFAbGKzTlKtg" crossorigin="anonymous"></script>
</head>
<body>
<h1>HtmxIndex</h1>
<form hx-post="/Home/Upload" hx-target="#upload-result" hx-encoding="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<button type="submit">Upload</button>
</form>
<div id="upload-result"></div>
</body>
</html>
After running the application, the result as below: