How to download multiple files? If the user sends a single file, display it, and if the user sends multiple files, how to set?
This is my controller code:
public IActionResult DownloadFile(int id)
{
byte[] bytes;
string fileName, contentType;
var model = new List<Files>();
var getdocument = _documentdata.GetDocumentbyDocumentId(id);
if (getdocument != null)
{
fileName = getdocument.Name;
contentType = getdocument.FileType;
bytes = getdocument.DataFiles;
return File(bytes, contentType: "application/octet-stream", fileName);
}
return Ok("Can't find the image");
}
Upload is working storing in database 2 tables when I click uploaded download?
Getting document single id
public Files GetDocumentbyDocumentId(int documentId)
{
var list = (from doc in _auc.Files
where doc.DocumentId == documentId
select doc).FirstOrDefault();
return list;
}
To download multiple file, you can create a zip file and add the multiple files inside it. Refer to the following sample:
In this sample, I will query the Products table and get their image content, then download them using a Zip file.
public IActionResult DownLoadAll()
{
var zipName = $"TestFiles-{DateTime.Now.ToString("yyyy_MM_dd-HH_mm_ss")}.zip";
using (MemoryStream ms = new MemoryStream())
{
//required: using System.IO.Compression;
using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
//QUery the Products table and get all image content
_dbcontext.Products.ToList().ForEach(file =>
{
var entry = zip.CreateEntry(file.ProImageName);
using (var fileStream = new MemoryStream(file.ProImageContent))
using (var entryStream = entry.Open())
{
fileStream.CopyTo(entryStream);
}
});
}
return File( ms.ToArray(), "application/zip", zipName);
}
}
Code in the Index page:
<a asp-controller="Product" asp-action="DownLoadAll">DownLoad All Images</a>
Products model:
public class Product
{
[Key]
public int ProId { get; set; }
public string ProName { get; set; }
public string ProImageName { get; set; }
public byte[] ProImageContent { get; set; } //Image content.
public string ProImageContentType { get; set; }
//you can add another properties
}
The output as below:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.