Get filename while downloading it

前端 未结 6 513
抹茶落季
抹茶落季 2020-12-13 13:59

We are providing files that are saved in our database and the only way to retrieve them is by going by their id as in:

www.AwesomeURL.com/AwesomeS

6条回答
  •  春和景丽
    2020-12-13 14:45

    Here is the full code required, assuming the server has applied content-disposition header:

    using (WebClient client = new WebClient())
    {
        using (Stream rawStream = client.OpenRead(url))
        {
            string fileName = string.Empty;
            string contentDisposition = client.ResponseHeaders["content-disposition"];
            if (!string.IsNullOrEmpty(contentDisposition))
            {
                string lookFor = "filename=";
                int index = contentDisposition.IndexOf(lookFor, StringComparison.CurrentCultureIgnoreCase);
                if (index >= 0)
                    fileName = contentDisposition.Substring(index + lookFor.Length);
            }
            if (fileName.Length > 0)
            {
                using (StreamReader reader = new StreamReader(rawStream))
                {
                    File.WriteAllText(Server.MapPath(fileName), reader.ReadToEnd());
                    reader.Close();
                }
            }
            rawStream.Close();
        }
    }
    

    If the server did not set up this header, try debugging and see what ResponseHeaders you do have, one of them will probably contain the name you desire. If the browser show the name, it must come from somewhere.. :)

提交回复
热议问题