11

i am new to ASP.net COre and i would like to upload a file ( an image) and store it in a secific Folder. ihave been following this tuto (File uploads in ASP.NET Core) but i dont know how to store it in a file it is just uploaded on the server this is the html :

<form method="post" enctype="multipart/form-data" asp-controller="UploadFiles" asp-action="Index">
<div class="form-group">
    <div class="col-md-10">
        <p>Upload one or more files using this form:</p>
        <input type="file" name="files" multiple />
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Upload" />
    </div>
</div>

this is the Controller

[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});
}

and this is the class i am using

public interface IFormFile
{
string ContentType { get; }
string ContentDisposition { get; }
IHeaderDictionary Headers { get; }
long Length { get; }
string Name { get; }
string FileName { get; }
Stream OpenReadStream();
void CopyTo(Stream target);
Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}

i just need to store the image in a folder like :C:\Users\DESKTOP-1603\Desktop\GestionSyndic\GestionSyndic\src\WebApplication1\wwwroot\images\ and change the name of the image thank you :D

3
  • We use IFormFile.OpenReadStream() and ImageSharp to validate it's an real image file. If you don't need this you can use this: stackoverflow.com/questions/411592/… Commented Nov 5, 2017 at 19:07
  • What you mean "store it in a file ? Did you mean, you want to store it in a specific folder in your app root ? Commented Nov 5, 2017 at 19:09
  • sorry i meant folder in my app root Commented Nov 5, 2017 at 19:11

3 Answers 3

17

File upload in ASP.NET Core MVC in simple steps

1.Demo.cshtml View Code snippet

<form method="post" enctype="multipart/form-data" asp-controller="Demo" asp-action="Index">
<div class="form-group">
    <div class="col-md-10">
        <p>Upload one or more files using this form:</p>
        <input type="file" name="files" multiple />
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Upload" />
    </div>
</div>

  1. DemoController

For showing demo i have created a Demo Controller which has 2 Action Methods in it one to handle Get Request and another to handle post request.

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Net.Http.Headers;

namespace WebApplication6.Controllers
{
    public class DemoController : Controller
    {
        private readonly IHostingEnvironment _environment;

        // Constructor
        public DemoController(IHostingEnvironment IHostingEnvironment)
        {
            _environment = IHostingEnvironment;
        }

        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(string name)
        {
            var newFileName = string.Empty;

            if (HttpContext.Request.Form.Files != null)
            {
                var fileName = string.Empty;
                string PathDB = string.Empty;

                var files = HttpContext.Request.Form.Files;

                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        //Getting FileName
                        fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                        //Assigning Unique Filename (Guid)
                        var myUniqueFileName = Convert.ToString(Guid.NewGuid());

                        //Getting file Extension
                        var FileExtension = Path.GetExtension(fileName);

                        // concating  FileName + FileExtension
                        newFileName = myUniqueFileName + FileExtension;

                        // Combines two strings into a path.
                        fileName = Path.Combine(_environment.WebRootPath, "demoImages") + $@"\{newFileName}";

                        // if you want to store path of folder in database
                        PathDB = "demoImages/" + newFileName;

                        using (FileStream fs = System.IO.File.Create(fileName))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                    }
                }


            }
            return View();
        }
    }
}

Snapshot while Debugging

Snapshot while Debuggin

Location of folder where Images are stored

Location of Folder where Images are Stored

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your esponse the problem i am facing now that i have added this code is that i can only subit the photo the model is no more submitted in the controller
the problem is i am not getting any error the model passed to the controller is just null here is the whole issue stackoverflow.com/questions/47319242/…
This code isn't portable, backslash works in Windows only, always use Path.Combine(): path += $@"\{newFileName}"; // wrong way
This code works, only with the exception on updating fileName. This line works for me on mac: fileName = Path.Combine(_environment.WebRootPath, "uploadImages") + $@"/{newFileName}";
5

You should inject IHostingEnvironment so you can get the web root (wwwroot by default) location.

public class HomeController : Controller
{
    private readonly IHostingEnvironment hostingEnvironment;
    public HomeController(IHostingEnvironment environment)
    {
        hostingEnvironment = environment;
    }
    [HttpPost]
    public async Task<IActionResult> UploadFiles(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)
        {
            var uploads = Path.Combine(hostingEnvironment.WebRootPath, "images");
            var fullPath = Path.Combine(uploads, GetUniqueFileName(formFile.FileName));
            formFile.CopyTo(new FileStream(fullPath, FileMode.Create));

        }
        return Ok(new { count = files.Count, size, filePath });
    }
    private string GetUniqueFileName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return  Path.GetFileNameWithoutExtension(fileName)
                  + "_" 
                  + Guid.NewGuid().ToString().Substring(0, 4) 
                  + Path.GetExtension(fileName);
    }
}

This will save the files to the images directory in wwwroot.

Make sure that your form tag's action attribute is set to the UploadFiles action method of HomeController(/Home/UploadFiles)

<form method="post" enctype="multipart/form-data" asp-controller="Home"
                                                  asp-action="UploadFiles">
    <div class="form-group">
        <div class="col-md-10">
            <p>Upload one or more files using this form:</p>
            <input type="file" name="files" multiple />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-10">
            <input type="submit" value="Upload" />
        </div>
    </div>
</form>

I am not very certain why you want to return Ok result from this. You may probably return a redirect result to the listing page.

Comments

0

Just used the accepted answer from @Saineshwar, but did a little bit refactoring as one extension method to make it easy to use IFromFile

public static string MakeFileUniqueName(this IFormFile formFile)
    {
        if (formFile.Length > 0)
        {
            string fileName =
                ContentDispositionHeaderValue.Parse(formFile.ContentDisposition).FileName.Trim('"');

            // concatinating  FileName + FileExtension
            return Guid.NewGuid() + Path.GetExtension(fileName);      
        }

        return string.Empty;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.