Home > Software engineering >  How can i save an input image in the wwwroot For ASP.NET MVC?
How can i save an input image in the wwwroot For ASP.NET MVC?

Time:07-12

So i have this this page in View:

    <div >

        <div >
            <h5>Scan a code</h5>
        </div>

        <div >
            <form asp-controller="Scanner" asp-action="ScannerDone" method="post">

                <div >
                    <input asp-for=Photo type="file" accept="image/*" capture="camera">
                    
                </div>

                <div >
                    <label >Content</label>
                    <input asp-for=Content type="text"  />
                </div>

                <div >
                    <label >Type</label>
                    <input asp-for=Type type="text"  />
                </div>

                <div >
                    <button type="submit" >Confirma</button>
                </div>

            </form>
        </div>

        <div >
        </div>

    </div>

</div>

My question is how do i save the image, thats gonna be selected, in the wwwroot directory? I been trying to find information about this on internet but all i found its a command named:HttpPostedFileBase which doesnt work in this new version of asp.net

CodePudding user response:

Since this might me .NET Core, you can use the IFormFile interface.

Your model should be changed accordingly:

public string Type { get; set; }
public string Content { get; set; }
public IFormFile File { get; set; }

Then, you can write your file using something like this

string path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", File.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
    await File.CopyToAsync(stream);
}

CodePudding user response:

Here is a simple demo about how to upload file in Asp.Net Core and store it in wwwroot, You can refer to it.

View

<div>
    <h4>Single File Upload</h4>

  @* The type of form needs to be multipart/form-data *@

    <form asp-action="Index" enctype="multipart/form-data" method="post">
        <input type="file" name="file"/>
        <button type="submit">submit</button>
    </form>
</div>

Controller

public class HomeController : Controller
{
    
    private readonly IWebHostEnvironment _environment;

    public HomeController(IWebHostEnvironment environment)
    {
        
        _environment = environment;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(IFormFile file)
    {
        
        string fileName = file.FileName;
        
        using (var fileStream = new FileStream(Path.Combine(_environment.WebRootPath,fileName), FileMode.Create))
        { 
           await file.CopyToAsync(fileStream);
        }
        
        
        //.........
        return RedirectToAction("Index");
    }
}
  • Related