【问题标题】:Download file Asp.Net下载文件 Asp.Net
【发布时间】:2015-10-12 12:07:07
【问题描述】:

我在文件系统中有.zip 文件。我想下载那个文件。到目前为止,我已经完成了

HttpContext.Current.Response.ContentType = "application/zip";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
            HttpContext.Current.Response.TransmitFile(zipName);
            HttpContext.Current.Response.End();

但它直接打开文件而不是保存它。保存的话怎么下载呢?

我也见过DownloadFile(String, String),但我的第一个论点是什么?

【问题讨论】:

标签: c# asp.net


【解决方案1】:

您必须压缩,然后从该 zip 中获取字节并传递它们

context.Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}.{1}", fileName, fileExtension));
context.Response.ContentType = "application/octet-stream";
context.Response.OutputStream.Write(zipBytesArray, 0, zipBytesArray.Length);
context.Response.End();

【讨论】:

  • 您必须从该 zip 中获取字节并传递它们。
  • 简短而简单的使用以下命令:byte [] data = File.ReadAllBytes("C:\\temp\\file.zip");
  • 仍在打开文件:(
  • 写下你的完整sn-p,因为这段代码有效,所以不是这个
【解决方案2】:

如果你想从远程服务器下载它,那么你可以简单地使用 WebClient 类

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFilePath, FileName);

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    int bufferSize = 1;

    Response.Clear();
    Response.AppendHeader("Content-Disposition:", "attachment; filename=" +filename);
    Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
    Response.ContentType = "application/download";

    byte[] ByteBuffer = new byte[bufferSize + 1];
    MemoryStream ms = new MemoryStream(ByteBuffer, true);
    Stream rs = req.GetResponse().GetResponseStream();
    byte[] bytes = new byte[bufferSize + 1];
    while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
    {
        Response.BinaryWrite(ms.ToArray());
        Response.Flush();
    }

【讨论】:

  • 为什么要映射路径先生?它在网络中,不在同一台服务器上。
  • @Imad:- 你必须从远程服务器下载文件?
  • @Imad:- 你可以使用 WebClient 类或者检查这个:codeproject.com/Tips/357660/…
猜你喜欢
  • 1970-01-01
  • 2015-06-24
  • 2011-02-25
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多