【发布时间】:2017-07-27 22:26:17
【问题描述】:
我有一个文件夹,其中有 3-4 pdf 文件。所以点击按钮时,我想将 PDF 文件下载为ZIP 文件。为此,我编写了以下代码
string strFilePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID + "\\" + SAP_ID + '_' + CANDIDATEID + ".pdf");
string strDirectory = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
if (Directory.Exists(strDirectory))
{
if (File.Exists(strFilePath + ".zip"))
{
var filestream = new System.IO.FileStream(strFilePath + ".zip", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(strFilePath + ".zip");
}
}
// ZipFile.CreateFromDirectory(strDirectory, strDirectory + ".zip");
var stream = new FileStream(strDirectory + ".zip", FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(strDirectory + ".zip");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;
但是点击按钮时,ZIP 没有被下载,浏览器只是加载。
请帮我看看是什么原因?
【问题讨论】:
-
你能检查一下zip文件是否是在服务器上创建的吗?
-
@minhhn2910:好的,让我检查一下!
-
@minhhn2910:不,现在当我调试我的代码时,在
var stream = new FileStream(strDirectory + ".zip", FileMode.Open);行出现{"Could not find file 'D:\\UserName\\VSATFINAL_353\\VSATTSSRSurvey\\UploadedFiles\\I-BR-RNCH-ENB-0243_C3.zip'.错误 -
@minhhn2910: 抱歉,实际上它是在这一行创建的
ZipFile.CreateFromDirectory(strDirectory, strDirectory + ".zip");我注释掉了那一行。但是当它已经存在时,它会给我带来错误。那我该怎么办呢? -
您使用的是 MVC 还是 Web 表单?如果您使用的是 MVC,请尝试 FileResult 或对于 Web 表单,请尝试 Response.TransmitFile