简体   繁体   中英

Download file Asp.Net

I have .zip file in file system. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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