0
  string FilePath = HttpUtility.UrlDecode(Request.QueryString.ToString());
   string[] s = FilePath.Split(new char[] { ',' });
   string path = s[0];
   string FileName = s[1];
    String str = HttpContext.Current.Request.Url.AbsolutePath;
      System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
      response.ClearContent();
      response.Clear();
      //  response.ContentType = "text/plain";
      response.AddHeader("Content-Disposition", "attachment; filename=" + FileName+ ";");
      response.TransmitFile(path+FileName);
      response.Flush();
      response.End();

以上是我从另一个页面获取音频文件位置的代码。音频文件位于远程机器上,可以使用 URL 访问,例如 http:\servername\audiofiles\filename.wav 。response.Transmit 和 .WriteFile 需要虚拟路径,而 response.Write() 不下载文件。如何提供绝对 url 而不是下载文件的虚拟路径

4

1 回答 1

0

从另一个地方找到我自己的答案:

     string FilePath = HttpUtility.UrlDecode(Request.QueryString.ToString());
    string[] s = FilePath.Split(new char[] { ',' });
    string path = s[0];
    string FileName = s[1];

    int bytesToRead = 10000;


    byte[] buffer = new Byte[bytesToRead];


    try
    {
        HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(path+FileName);

        HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

        if (fileReq.ContentLength > 0)
            fileResp.ContentLength = fileReq.ContentLength;


        stream = fileResp.GetResponseStream();


        var resp = HttpContext.Current.Response;


        resp.ContentType = "application/octet-stream";

        resp.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + "\"");
        resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

        int length;
        do
        {
            if (resp.IsClientConnected)
            {
                // Read data into the buffer.
                length = stream.Read(buffer, 0, bytesToRead);

                // and write it out to the response's output stream
                resp.OutputStream.Write(buffer, 0, length);


                resp.Flush();

                //Clear the buffer
                buffer = new Byte[bytesToRead];
            }
            else
            {
                // cancel the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }
}
于 2012-10-25T15:09:39.790 回答