'ASP.NET MVC - how to zip and download files from database?
I'm new to ASP.NET MVC and I'm trying to figure out how to zip and download files stored in a database.
Do I need to zip the files, save them in memory or server, and then send that file to the user. I would rather not save it on the server.
Model:
public class Document
{
public int Id { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
}
Controller:
[HttpPost]
[Route("~/document/zip/{token}")]
public ActionResult DownloadZip(string token)
{
// EF6
var docs = db.Documents.ToList();
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var doc in docs)
{
var file = archive.CreateEntry(doc.Name.ToString());
using (var streamWriter = new StreamWriter(file.Open()))
{
streamWriter.Write(doc.Name.ToString());
}
}
}
return File(memoryStream.ToArray(), "~/WebApplication/Documents", "xxxx.zip");
};
}
Solution 1:[1]
If you want put your content to file, you have to take stream from file.Open()
and write byte array to this stream
[HttpPost]
[Route("~/document/zip/{token}")]
public ActionResult DownloadZip(string token)
{
// EF6
var docs = db.Documents.ToList();
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var doc in docs)
{
var file = archive.CreateEntry(doc.Name.ToString());
using (var stream = file.Open())
{
stream.Write(doc.Content, 0, doc.Content.Length);
}
}
}
return File(memoryStream.ToArray(), "application/zip", "xxxx.zip");
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |