Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.Net Core Upload Multiple Files , Zip and Save as a byte array in database
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.IO.Compression;
namespace MyNameSpace
{
public static class FileUpload
{
public static byte[] ToZip(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location: var filePath = Path.GetTempFileName();
var tempPath = Path.GetTempPath();
var filePath = tempPath + "/submission/";
var archiveFile = tempPath + "/zip/archive.zip";
var archivePath = tempPath + "/zip/";
if (Directory.Exists(filePath))
{
Directory.Delete(filePath, true);
}
if (Directory.Exists(archivePath))
{
Directory.Delete(archivePath, true);
}
Directory.CreateDirectory(filePath);
Directory.CreateDirectory(archivePath);
foreach (var formFile in files)
{
var fileName = filePath + formFile.FileName;
if (formFile.Length > 0)
{
using (var stream = new FileStream(fileName, FileMode.Create))
{
formFile.CopyToAsync(stream);
}
}
}
ZipFile.CreateFromDirectory(filePath, archiveFile);
/* beapen: 2017/07/24
*
* Currently A Filestream cannot be directly converted to a byte array.
* Hence it is copied to a memory stream before serializing it.
* This may change in the future and may require refactoring.
*
*/
var stream2 = new FileStream(archiveFile, FileMode.Open);
var memoryStream = new MemoryStream();
stream2.CopyTo(memoryStream);
using (memoryStream)
{
return memoryStream.ToArray();
}
}
}
}
@abhee1996

This comment has been minimized.

Show comment
Hide comment
@abhee1996

abhee1996 Jul 14, 2018

Please tell me how do i use this code in my project
im newbee

abhee1996 commented Jul 14, 2018

Please tell me how do i use this code in my project
im newbee

@abhee1996

This comment has been minimized.

Show comment
Hide comment
@abhee1996

abhee1996 Jul 14, 2018

I'm using Asp.net core 2.0

abhee1996 commented Jul 14, 2018

I'm using Asp.net core 2.0

@abhee1996

This comment has been minimized.

Show comment
Hide comment
@abhee1996

abhee1996 Jul 14, 2018

how do I use it in my scenario
//My Model Register.cs
public byte[] UploadImg { get; set; }
//Context class
public DbSet register { get; set; }
//my controller
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SPA_App.Models;
using System.Globalization;
using Microsoft.AspNetCore.Http;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;

namespace SPA_App.Controllers
{
public class RegistersController : Controller
{
private readonly StudentContext _context;

    public RegistersController(StudentContext context)
    {
        _context = context;
    }

    // GET: Registers
    public async Task<IActionResult> Index()


    {
        return View(await _context.register.ToListAsync());
    }

    // GET: Registers/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var register = await _context.register
            .SingleOrDefaultAsync(m => m.RegId == id);
        if (register == null)
        {
            return NotFound();
        }

        return View(register);
    }

    // GET: Registers/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Registers/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    //[ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("RegId,StudyLevel,RegFName,RegMidName,RegLastName,DoB,JoiningDate,RegEmail,Phone,Gender,Cource,Nationallity,State,Address,tel,Monthlyfees,UploadImg")] Register register)
    {
        if (ModelState.IsValid)
        {
            _context.Add(register);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(register);
    }

    // GET: Registers/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var register = await _context.register.SingleOrDefaultAsync(m => m.RegId == id);
        if (register == null)
        {
            return NotFound();
        }
        return View(register);
    }

    // POST: Registers/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
   // [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("RegId,StudyLevel,RegFName,RegMidName,RegLastName,DoB,JoiningDate,RegEmail,Phone,Gender,Cource,Nationallity,State,Address,tel,Monthlyfees,UploadImg")] Register register)
    {
        if (id != register.RegId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(register);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RegisterExists(register.RegId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(register);
    }

    // GET: Registers/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var register = await _context.register
            .SingleOrDefaultAsync(m => m.RegId == id);
        if (register == null)
        {
            return NotFound();
        }

        return View(register);
    }

    // POST: Registers/Delete/5
    [HttpPost, ActionName("Delete")]
  //  [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var register = await _context.register.SingleOrDefaultAsync(m => m.RegId == id);
        _context.register.Remove(register);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool RegisterExists(int id)
    {
        return _context.register.Any(e => e.RegId == id);
    }


   
}

}

abhee1996 commented Jul 14, 2018

how do I use it in my scenario
//My Model Register.cs
public byte[] UploadImg { get; set; }
//Context class
public DbSet register { get; set; }
//my controller
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SPA_App.Models;
using System.Globalization;
using Microsoft.AspNetCore.Http;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;

namespace SPA_App.Controllers
{
public class RegistersController : Controller
{
private readonly StudentContext _context;

    public RegistersController(StudentContext context)
    {
        _context = context;
    }

    // GET: Registers
    public async Task<IActionResult> Index()


    {
        return View(await _context.register.ToListAsync());
    }

    // GET: Registers/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var register = await _context.register
            .SingleOrDefaultAsync(m => m.RegId == id);
        if (register == null)
        {
            return NotFound();
        }

        return View(register);
    }

    // GET: Registers/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Registers/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    //[ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("RegId,StudyLevel,RegFName,RegMidName,RegLastName,DoB,JoiningDate,RegEmail,Phone,Gender,Cource,Nationallity,State,Address,tel,Monthlyfees,UploadImg")] Register register)
    {
        if (ModelState.IsValid)
        {
            _context.Add(register);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(register);
    }

    // GET: Registers/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var register = await _context.register.SingleOrDefaultAsync(m => m.RegId == id);
        if (register == null)
        {
            return NotFound();
        }
        return View(register);
    }

    // POST: Registers/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
   // [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("RegId,StudyLevel,RegFName,RegMidName,RegLastName,DoB,JoiningDate,RegEmail,Phone,Gender,Cource,Nationallity,State,Address,tel,Monthlyfees,UploadImg")] Register register)
    {
        if (id != register.RegId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(register);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RegisterExists(register.RegId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(register);
    }

    // GET: Registers/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var register = await _context.register
            .SingleOrDefaultAsync(m => m.RegId == id);
        if (register == null)
        {
            return NotFound();
        }

        return View(register);
    }

    // POST: Registers/Delete/5
    [HttpPost, ActionName("Delete")]
  //  [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var register = await _context.register.SingleOrDefaultAsync(m => m.RegId == id);
        _context.register.Remove(register);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool RegisterExists(int id)
    {
        return _context.register.Any(e => e.RegId == id);
    }


   
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment