netcore 從api下載文件並直接返回


[HttpGet]
        public IActionResult HttpReturnFile()
        {
            string url = "http://localhost:99/api/HttpFile/GetFile";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            using (WebResponse webRes = request.GetResponse())
            {
                int length = (int)webRes.ContentLength;
                HttpWebResponse response = webRes as HttpWebResponse;
                Stream stream = response.GetResponseStream();
                var contentdisposition = response.Headers["Content-Disposition"];
                var filename = Util.Midstr(contentdisposition, "filename=", ";");
                var ext = "."+filename.Split('.')[1];
                new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
                //讀取到內存
                MemoryStream stmMemory = new MemoryStream();
                byte[] buffer = new byte[length];
                int i;
                //將字節逐個放入到Byte中
                while ((i = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stmMemory.Write(buffer, 0, i);
                }
                stmMemory.Close();
                return File(buffer, contenttype ?? "application/octet-stream",filename);
            }
        }

 url下載文件地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM