netcore 从api下载文件到本地
public IActionResult HttpDownFile() { string url = "http://localhost:99/api/HttpFile/GetFile"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; byte[] fileBytes; 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=", ";"); //读取到内存 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); } fileBytes = stmMemory.ToArray();//文件流Byte FileStream fs = new FileStream("D:\\other\\Test\\"+filename, FileMode.OpenOrCreate); stmMemory.WriteTo(fs); stmMemory.Close(); fs.Close(); return Ok("D:\\other\\Test\\" + filename); } }
url是下载文件的地址