簡體   English   中英

如何在 ASP.NET Core MVC 中下載多個文件

[英]How to download multiple files in ASP.NET Core MVC

如何下載多個文件? 如果用戶發送單個文件,顯示,如果用戶發送多個文件,如何設置?

這是我的 controller 代碼:

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");
}

當我單擊上傳下載時,上傳是否正在存儲在數據庫 2 個表中?

獲取文檔單一ID

public Files GetDocumentbyDocumentId(int documentId)
{
    var list = (from doc in _auc.Files
                where doc.DocumentId == documentId
                select doc).FirstOrDefault();
    return list;
}

要下載多個文件,您可以創建一個 zip 文件並在其中添加多個文件。 請參考以下示例:

在此示例中,我將查詢 Products 表並獲取它們的圖像內容,然后使用 Zip 文件下載它們。

    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); 
        }
    }

索引頁面中的代碼:

<a asp-controller="Product" asp-action="DownLoadAll">DownLoad All Images</a>

產品 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
}

output如下:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM