webapi2.0文件下载

发布时间 2023-03-27 15:25:20作者: 沈先生爱猫咪
  [System.Web.Http.Route("api/download")]
        public HttpResponseMessage GetFile(string filePath)
        {
            try
            {
                filePath = "\\" + filePath;
          
                var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(filePath);
                var stream = new FileStream(FilePath, FileMode.Open);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = Path.GetFileName(FilePath)
                };
                return response;
            }
            catch(Exception ex)
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }