我正在使用处理程序(.ashx)来提供一些文件。我有一个文件夹,我存储电子书。我用书PK命名它们,每本书可能有几种不同的格式:
211.html
211.pdf
211.prc
以下测试代码成功下载了一本书。
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=myfile.pdf");
context.Response.TransmitFile(context.Server.MapPath("~/Media/eBooks/212.pdf"));
我如何为客户提供三种不同的格式? (客户现有组织不在文件夹中)
我试图做这样的事情:
DirectoryInfo bookDir = new DirectoryInfo(context.Server.MapPath("~/Media/eBooks"));
FileInfo[] f = bookDir.GetFiles();
foreach (var n in f)
{
context.Response.AppendHeader("Content-Disposition", "attachment;filename=myfile.pdf");
context.Response.TransmitFile(context.Server.MapPath("~/Media/eBooks/212.pdf"));
}
但它会下载一个没有文件扩展名的文件。
答案 0 :(得分:8)
在一个响应中发送多个文件的唯一方法是将它们放在存档包中,例如:一个.zip
文件。 那至少可以用代码完成,使用各种工具(IIRC现在主.NET框架中有一个zip包装器;否则,SharpZipLib可以很好地完成这项工作)。
答案 1 :(得分:1)
要发送多个要下载的文件,您应该使用sharpziplib或其他文件压缩实用程序压缩它们,文件应该压缩然后下载链接可以发送到客户端立即下载它们。下面的代码使用ICSharpCode.SharpZipLib.dll库。 您可以调用此类并传递要压缩的文件。
public string Makezipfile(string[] files)
{
string[] filenames = new string[files.Length];
for (int i = 0; i < files.Length; i++)
filenames[i] = HttpContext.Current.Request.PhysicalApplicationPath + files[i].Replace(HttpContext.Current.Request.UrlReferrer.ToString(), "");
string DirectoryName = filenames[0].Remove(filenames[0].LastIndexOf('/'));
DirectoryName = DirectoryName.Substring(DirectoryName.LastIndexOf('/') + 1).Replace("\\", "");
try
{
string newFile = HttpContext.Current.Request.PhysicalApplicationPath + "your image directory\\" + DirectoryName + ".zip";
if (File.Exists(newFile))
File.Delete(newFile);
using (ZipFile zip = new ZipFile())
{
foreach (string file in filenames)
{
string newfileName = file.Replace("\\'", "'");
zip.CompressionLevel = 0;
zip.AddFile(newfileName, "");
}
zip.Save(newFile);
}
}
catch (Exception ex)
{
//Console.WriteLine("Exception during processing {0}", ex);
Response.Write(ex);
// No need to rethrow the exception as for our purposes its handled.
}
string a;
a = "your images/" + DirectoryName + ".zip";
return a;
}
答案 2 :(得分:1)
我承认这里提到的好的Zip解决方案,但是你可以使用javascript / XHR对处理程序进行3次调用,每次请求不同的文件格式吗?
不可否认,您受到浏览器支持的并发请求数量的限制,但我相信浏览器会将请求排队超过限制。
好处是用户不需要处理zip文件,这可能会使他们感到困惑。相反,他们应该下载3次。