首页 > 解决方案 > Download Multiple Uploaded Files

问题描述

I uploaded multiple files as bytes into database table and how to download files as zip now? My code as below: View:

@using (Html.BeginForm(Html.BeginForm("upload", "Home", FormMethod.Post, new { @id = "form", enctype = "multipart/form-data" })))
        {
            <input type="file" multiple="multiple" name="files" id="files" />
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Submit" class="btn btn-default" />
                </div>
            </div>
        }

controller:

    public FileContentResult GetFile(int id)
    {
        
        SqlDataReader rdr; byte[] fileContent = null;
        string mimeType = ""; string fileName = "";
        string constr = WebConfigurationManager.ConnectionStrings["DbContextModel"].ConnectionString;

        using (SqlConnection con = new SqlConnection(constr))
        {
            var qry = "SELECT * FROM myTable WHERE ID = @ID";
            var cmd = new SqlCommand(qry, con);
            cmd.Parameters.AddWithValue("@ID", id);
            con.Open();
            rdr = cmd.ExecuteReader();
            if (rdr.HasRows)
            {
                rdr.Read();
                fileContent = (byte[])rdr["Attachments"];

            }
        }
        return File(fileContent, "application/zip", "download.zip");
        
    }

Model:

  public partial class myTable
 {
  public int id {get;set;}
  public byte[] Attachments { get; set; }
  }

The download.zip file cannot be opened. "The compressed zipped folder is invalid". Please advise. Thanks in advance.

upload function:

...
     byte[] bytes = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
            MemoryStream target = new MemoryStream();
            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                { 
                     file.InputStream.CopyTo(target);
                    bytes = target.ToArray();
               
                }
                
            }

标签: asp.net-mvc

解决方案


将每个上传文件的数据附加到单个流中不会创建有效的 zip 文件。您需要生成一个有效的 zip 文件以存储在数据库中。

例如:

byte[] bytes;
var target = new MemoryStream();
using (var zip = new ZipArchive(target, ZipArchiveMode.Create, true))
{
    foreach (var file in files)
    {
        string name = Path.GetFileName(file.FileName);
        ZipArchiveEntry entry = zip.CreateEntry(name);
        using (Stream entryStream = entry.Open())
        {
            file.InputStream.CopyTo(entryStream);
        }
    }
    
    bytes = target.ToArray();
}

ZipArchive 类


推荐阅读