Open
deneme

Fileupload Çeşitleri

enctype (ENCodeTYPE) niteliği, form verilerinin sunucuya gönderilirken nasıl kodlanması gerektiğini belirtir.
multipart/form-data , dosya yüklemesi olduğunu bildirir.
.Net provides us with an Interface called IFormFile
Lets type in make a using statement and make a file stream
First thing we need to add a path.
and a file mode which is going to be create and a file access.


Single File Upload

using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace Asp.Net.Core.Controllers
{
public class HomeController : Controller
{
    private IHostingEnvironment env; 
    public HomeController(IHostingEnvironment _env)
    {
        env = _env; 
    }
    public IActionResult Index() => View();

    public IActionResult SingleFile(IFormFile prm_file)
    {
        string directory = env.ContentRootPath;
        using (var fileStream = new FileStream(Path.Combine(directory, "file.png"), FileMode.Create, FileAccess.Write))
        {
            prm_file.CopyTo(fileStream);
        }
        return RedirectToAction("Index");
    }
<form asp-controller="Home" asp-action="SingleFile" method="post" enctype="multipart/form-data">
    <input type="file" name="prm_file" />
    <button type="submit">Submit</button>
</form>



Multiple File Upload

public class HomeController : Controller
{
    private IHostingEnvironment env;
    private string dir;
    public HomeController(IHostingEnvironment _env)
    {
        env = _env;
        dir = env.ContentRootPath;
    }
public IActionResult MultipleFile(IEnumerable<IFormFile> prm_files)
{
    int i = 0;
    foreach (var item in prm_files)
    {
        using (var fileStream = new FileStream(Path.Combine(dir, $"prm_files{i++}.png"), FileMode.Create, FileAccess.Write))
        {
            item.CopyTo(fileStream);
        }
        i++;
    }
    return RedirectToAction("Index");
}
}
<form asp-controller="Home" asp-action="MultipleFile" method="post" enctype="multipart/form-data">
    <input type="file" multiple name="prm_files" />
    <button type="submit">Submit</button>
</form>




FileUpload to wwwRoot folder

public IActionResult RootFile(IFormFile prm_file)
{
    var path = Path.Combine("wwwroot/images");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

    using (var fileStream = new FileStream(Path.Combine(path, prm_file.FileName), FileMode.Create, FileAccess.Write))
    {
        prm_file.CopyTo(fileStream);
    }
    return RedirectToAction("Index");
}
<form asp-controller="Home" asp-action="RootFile" method="post" enctype="multipart/form-data">
    <input type="file" name="prm_file" />
    <button type="submit">Submit</button>
</form>




Upload file with custom name

public IActionResult CustomFile(IFormFile prm_file)
{
    var path = Path.Combine("wwwroot/css");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    var img_mime = prm_file.FileName.Substring(prm_file.FileName.LastIndexOf('.'));
    var filename = $"img_{DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss")}{img_mime}";

    using (var fileStream = new FileStream(Path.Combine(path, filename), FileMode.Create, FileAccess.Write))
    {
        prm_file.CopyTo(fileStream);
    }
    return RedirectToAction("Index");
}
<form asp-controller="Home" asp-action="CustomFile" method="post" enctype="multipart/form-data">
    <input type="file" name="prm_file" />
    <button type="submit">Submit</button>
</form>



File in Model

using Microsoft.AspNetCore.Http;
namespace Asp.Net.Core.ViewModels
{
    public class FormFileVM
    {
      public string Name { get; set; }
      public IFormFile File { get; set; }
    }
}
public IActionResult FileInModel(FormFileVM formfilevm)
{
    var path = Path.Combine("wwwroot/images");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    using (var fileStream = new FileStream(Path.Combine(path , formfilevm.Name),
                                           FileMode.Create, FileAccess.Write))
    {
        formfilevm.File.CopyTo(fileStream);
    }
    return RedirectToAction("Index");
}

<form asp-controller="Home" asp-action="FileInModel" method="post" enctype="multipart/form-data">
    <input type="file" name="formfilevm.File" />
    <input type="text" name="formfilevm.Name" />
    <button type="submit">Submit</button>
</form>



Single File Upload with axios javascript

using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace Asp.Net.Core.Controllers
{
public class HomeController : Controller
{
    private IHostingEnvironment env; 
    public HomeController(IHostingEnvironment _env)
    {
        env = _env; 
    }
    public IActionResult Index() => View();

    public IActionResult SingleFile(IFormFile prm_file)
    {
        string directory = env.ContentRootPath;
        using (var fileStream = new FileStream(Path.Combine(directory, "file.png"), FileMode.Create, FileAccess.Write))
        {
            prm_file.CopyTo(fileStream);
        }
        return RedirectToAction("Index");
    }
Extra view part
script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js">/script>
input type="file" onchange="uploadFile(event)"  />
 <script>
     var uploadFile = function (e) { console.log(e); }
 </script>

On Console U can see :Event {isTrusted: true, type: "change", target: ınput, currentTarget: ınput, eventPhase: 2, …}


the main view part
input type="file" onchange="uploadFile(event)"  />
script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js">/script>
 <script>
     var uploadFile = function (e)
     {
         var file = e.target.files[0];
         var formData = new FormData();
         formData.append("prm_file", file);
         axios.post("/Home/SingleFile", formData);
     }
Not: to make asynchronous javascript requests we use Axious library
U can use @RenderSection("scripts"); in Layout and in this page u can say @section scripts{ }



Multiple File Upload with axios javascript
public IActionResult MultipleFile(IEnumerable<IFormFile> prm_files)
{
    int i = 0;
    foreach (var item in prm_files)
    {
        using (var fileStream = new FileStream(Path.Combine(dir, $"prm_files{i++}.png"), FileMode.Create, FileAccess.Write))
        {
            item.CopyTo(fileStream);
        }
        // comment when you use anxios multiple i++;
    }
    return RedirectToAction("Index");
}
<input type="file" onchange="uploadFiles(event)" multiple />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
 <script>
     var uploadFiles = function (e)
     {
         var files = e.target.files;
         var formData = new FormData();
         for (var i = 0; i < files.length; i++) {
             formData.append("prm_files", files[i]);
         }
         axios.post("/Home/MultipleFile", formData);
     }
 </script>
02.02.2020