klabautermann123
7/25/2017 - 6:14 AM

Get FileStream from WebAPI2

Get FileStream from WebAPI2

 [HttpGet]
        [ActionName("GetReport")]
        public HttpResponseMessage GetReport([FromUri] string environment)
        {
            // http://localhost:50841/api/report/getreport?environment=QS

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

            var serverPath = AppDomain.CurrentDomain.BaseDirectory;
            var outputFileName = "Report_Zielplan.xlsm";
            var excelFileName = Path.Combine("reports", environment, outputFileName);
            
            //@"reports\" + environment + @"\Report_Zielplan.xlsm";
            var fileInfo = new FileInfo(Path.Combine(serverPath, excelFileName));

            if (fileInfo.Exists)
            {
                var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = outputFileName
                };

            }
            else
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Die angegebene Datei exixtiert nicht. Dateiname:  " + fileInfo.FullName);
            }

            return result;

        }