简体   繁体   English

下载文件Asp.Net

[英]Download file Asp.Net

I have .zip file in file system. 我在文件系统中有.zip文件。 I want to download that file. 我要下载该文件。 So far I have done 到目前为止,我已经完成了

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

But it directly opens up the file rather than saving it. 但是它直接打开文件而不是保存文件。 How can download it instead if saving? 保存后如何下载呢?

I have also seen DownloadFile(String, String) but what will be first argument in my case? 我也看过DownloadFile(String, String)但是在我的情况下,第一个参数是什么?

You have to zip and than get the bytes from that zip and pass them 您必须压缩,然后从该压缩中获取字节并将其传递

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();

In case you want to download it from the remote server then you can simply use the WebClient class 如果您想从远程服务器下载它,则只需使用WebClient类

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

or 要么

    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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM