I want to download a file with my controller :
public HttpResponseMessage GetFileConverted(string fileName)
{
if (String.IsNullOrEmpty(fileName))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream((filePath + fileName), FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
I did a test :
But it wasn't working because of the file extension .pdf For example when my fileName was equal to "test" it was working. But when I tried to put the ".pdf" it create issues.
So I changed my controller to this :
public HttpResponseMessage GetFile(string fileName)
{
if (String.IsNullOrEmpty(fileName))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream((filePath + fileName + ".pdf"), FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
And now I just put my file name without extension in my url to download him.
But I think there is a better way to resolve this kind of issue. Can you give me advice or documentation. Because Didn't found anything about this problem.