c# webapi 返回指定ContentType

tech2023-05-29  49

c# webapi 返回指定ContentType

//文件虚拟路径 string path = System.Web.Hosting.HostingEnvironment.MapPath(@"~/"); //存放的测试文件 System.IO.FileStream fs = new System.IO.FileStream(path + "47.png", System.IO.FileMode.Open, System.IO.FileAccess.Read); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); HttpContent content = new StreamContent(fs); content.Headers.Add("Content-Type", "text / plain"); //告诉浏览器是下载而不是打开文件 content.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("name.png")); result.Content = content; return result; [HttpGet] public HttpResponseMessage GetID() { string path = System.Web.Hosting.HostingEnvironment.MapPath(@"~/"); //Stream fs = new FileStream(path + "2.PNG", FileMode.Open); System.IO.FileStream fs = new System.IO.FileStream(path + "47.png", System.IO.FileMode.Open, System.IO.FileAccess.Read); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(fs), }; result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain"); //告诉浏览器是下载而不是打开文件 result.Content.Headers.ContentDisposition =new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "newWoman.png"//文件名,默认值为控制器名称 }; return result; }
最新回复(0)