【发布时间】:2018-09-18 18:43:05
【问题描述】:
我想创建一个循环来遍历我的数据库中具有特定 ID 的所有文件,并以zip-格式下载它们。每个文件都有一个名称。我想按名称 + timenow 将其保存在单个 zipfile 中。
//this code is working fine for single file
if (fileattach != null && fileattach.ContentLength > 0)
fileattach.FileDownloadName = attach.name + System.DateTime.Now + ".jpg";
return fileattach;
我尝试如下做,但我真的没有逻辑
public ActionResult downloadF(int? id) {
var attach = db.details.First(a => a.id == id);
var fileattach = new FileContentResult(attach.foto.ToArray(), "application/octet-stream");
var fileattach2 = new FileContentResult(attach.passport.ToArray(), "application/octet-stream");
var fileattach3 = new FileContentResult(attach.degree.ToArray(), "application/octet-stream");
using (var memoryStream = new MemoryStream()) {
using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
for (int i = 0; i < 3; i++) {
//how to define files object as we do in the upload by defining
//HttpPostedFileBase here it is not working
HttpPostedFileBase Files.ElementAt(i) != null
ziparchive.CreateEntryFromFile(filesCol[i].name);
}
}
return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
}
【问题讨论】:
-
HttpPostedFileBase用于浏览器向您发送文件时。您不应该在这里使用它,因为您正在向浏览器 提供文件。 -
可以通过以下两种方式之一将数据库中的文件添加到 zip 文件中。 a) 您将它们保存到文件系统,然后将它们从那里添加到 zip 文件中。 b) 您可以通过
Stream将它们添加到 zip 文件中。你知道我说的Stream是什么意思吗? -
如何对多文件使用流,我面临的问题是如何在如上图选择id时遍历数据库中的所有文件,
-
它是 var attach = db.details.Where(a => a.id == id); ,表示dbset在数据库中的确切行,下一步如何下载foto,passport,degree列中存在的任何文件
-
使用
MemoryStream而不是FileContentResult。
标签: c# asp.net-mvc downloadfile