HttpResponseMessage 文件流

   /// <summary>
        /// 文件获取
        /// </summary>
        /// <returns></returns>
        [MapToApiVersion("1.0")]
        [Route("v{version:apiVersion}/GetFile")]
        public HttpResponseMessage GetFile(string FilePath)
        {
            FileStream fileStream = null;
            try
            {
                var browser = String.Empty;
                if (HttpContext.Current.Request.UserAgent != null)
                {
                    browser = HttpContext.Current.Request.UserAgent.ToUpper();
                }
                FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath;
                HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
                fileStream = File.OpenRead(FilePath);
                // 读取文件的 byte[]  
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close(); // 把 byte[] 转换成 Stream  
                FileInfo f = new FileInfo(FilePath);
                if (f.Exists)
                {
                    f.Delete();
                }
                Stream stream = new MemoryStream(bytes);
                httpResponseMessage.Content = new StreamContent(stream);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName =
                        browser.Contains("FIREFOX")
                            ? Path.GetFileName(FilePath)
                            : HttpUtility.UrlEncode(Path.GetFileName(FilePath))
                };
 
                return httpResponseMessage;
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }

 

posted @ 2021-12-21 17:50  vba是最好的语言  阅读(192)  评论(0)    收藏  举报