Initially in View, define button that triggers to download files.
<a href="@Url.Action("ControllerMethod", "ControllerName", new {id = 12}) " class="btn btn-success"><i class="fa fa-download"></i> Export File </a>
- In View, like above, we define button which trigger the method in Controller. In @Url.Action firstly define Controlller method name, after that, define Controller name. If we want to send parameter to controller method, wecan specify it like this 'new {id=12} '. Use <i class="fa fa-download"></i> to get an download icon object on button.
In Controller:
You can reach parameter value with id which we can specify like this in View. To get Zip file we should include System.IO.Compression namespace and add System.IO.Compression.dll to project.
We will use ZipArchive.CreateEntry method to create an empty entry in the zip archive.
To get more please visit link.
public ActionResult ControllerMethod(int id)
{
using (var compressedFileStream = new MemoryStream())
{
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
{
//get list of file
var listOfFile = _servis.GetListOfFiles(id);
int i = 1;
//loop all the files which export
foreach (var file in listOfFile )
{
//get file name
string fileName = file.fileName;
var zipEntry11 = zipArchive.CreateEntry(fileName);
if (file != null)
{
//get file content
using (var originalFileStream = new MemoryStream(file.fileContent.ToArray()))
{
using (var zipEntryStream = zipEntry11.Open())
{
await originalFileStream.CopyToAsync(zipEntryStream);
}
}
}
i++;
}
}
//Add multiple file in a zip file
return File(compressedFileStream.ToArray(), "application/zip", "FileName.zip");
}
}
No comments:
Post a Comment