asp.net-mvc - 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();
}
}
解决方案
将每个上传文件的数据附加到单个流中不会创建有效的 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();
}
推荐阅读
- android - 如果指定了数据类型,则隐式意图找不到活动
- html - 使父 div 宽度与子 div 宽度相同
- c# - 使用位掩码识别特定的二进制数
- azure - Azure CLI 和 Powershell cmdlet 之间的功能不一致
- html - Bootstrap `justify-content-center` 在没有明确列号的情况下不会居中
- javascript - 如何从 index.html 向 Vue.js 3 实例发送消息?
- python-3.x - 当用户更改下拉过滤器中的值时,Django过滤更新查询
- sql-server - COM+ VB6 应用程序:RM_ENLIST_FAILED_TOO_MANY_ENLISTS 错误
- blazor - 检查 Blazor 应用程序是 WebAssembly 还是服务器?
- terraform - terraform 与一个状态文件的协作