![]() |
Hello Friends In this article, we will create a application for download all media file’s in zip format. We have to follow some simple steps to create a project and export some files in zip format in ASP.NET MVC
Step 1 – Create a Project
Opening Visual Studio, next, we need to create an ASP.NET MVC project. For doing that, just click File – New – Project.
After choosing a project, a new dialog will pop up. In that, select ASP.NET Web Application in the Web tab and give your project the location and a name. Then, click the “Ok” button. Choose the MVC Template.
Step 2: Install the SharpZipLib from Nuget package console
Install-Package SharpZipLib
Step 3 – Create a Action Method in Controller for Download zip file
Write code into Our DownloadZipController and give Media file path into List for Media file that you want to download in the zip file and create a folder named DownloadedMedia in root directory. Right now, I gave the static image path but you can set dynamic image path according to your requirements.
using System;
using System.Drawing;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using ICSharpCode.SharpZipLib.Zip;
namespace DownloadZipProject.Controllers
{
public class DownloadZipController:Controller
{
private DataAccessLayer _db = new DataAccessLayer ();
public FileResult DownloadMediaFilesInZip ()
{
var FileName = string.Format ("{1}_AllDocumentsFiles_{0}.zip",
DateTime.Today.
Date.ToString ("dd-MM-yyyy") + "_1",
SessionManager.ApplicantUserName);
var OutPutTempPath =
Server.MapPath (Url.Content ("/DownloadedMedia/") + FileName;
using (ZipOutputStream s =
new ZipOutputStream (System.IO.File.Create
(OutPutTempPath)))
{
s.SetLevel (9);
/byte[]buffer = new byte[4096];
var AllMediaList = new List < string > ();
DataSet ds = _db.RecruitmentApplicationPrint ();
var MediaFilesList = ds.Tables[0];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
MediaFilesList.Add (Server.MapPath
(ds.Tables[1].Rows[i]["DocPath"].
ToString ()));}
for (int i = 0; i < MediaFilesList.Count; i++)
{
ZipEntry entry =
new ZipEntry (Path.GetFileName (MediaFilesList[i]));
entry.DateTime = DateTime.Now;
entry.IsUnicodeText = true; s.PutNextEntry (entry);
using (FileStream fs =
System.IO.File.OpenRead (MediaFilesList[i]))
{
int sourceBytes;
do
{
sourceBytes = fs.Read (buffer, 0, buffer.Length);
s.Write (buffer, 0, sourceBytes);}
while (sourceBytes > 0);}
}
s.Finish (); s.Flush (); s.Close ();}
byte[]finalResult =
System.IO.File.ReadAllBytes (OutPutTempPath);
if (System.IO.File.Exists (OutPutTempPath)) System.IO.
File.Delete (OutPutTempPath);
if (finalResult == null
|| !finalResult.
Any ())throw new Exception (String.
Format
("No Media File found"));
return File (finalResult, "application/zip",
fileName);}
}
Step 4 – Implement button on view page for download Media files from the view side
<a href="@Url.Action("DownloadMediaFilesInZip", "DownloadZip")" class="btn btn-danger btn-rounded">Do








0 comments:
Post a Comment