I have use a method and retrieve files stored from Database without any problem in my project build on ASP.NET MVC and Angular:
[HttpPost]
public ActionResult GetFile(int id)
{
var file= service.GetFileById(id);
if (file.Data != null)
{
return File(file.Data, file.MimeType, file.Name);
}
return new EmptyResult();
}
On the other hand, when I want to use the same approach in my Web Api Controller, there is not such a kind of File() method and I tried to use the following method after looking at 15-20 solution on stackoverflow:
[Route("api/Generate/{id}")]
[AcceptVerbs("GET", "POST")]
public HttpResponseMessage Generate(int id)
{
var data = service.GetFileByName(id);
var stream = new MemoryStream();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = data.Name
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue(data.MimeType);
return result;
}
However, there is no extension of the downloaded files and I have not found a useful method in order o get file extension from mime type as shown below (this method gets file type from application/pdf, but cannot get if the mime type is application/octet-stream. So, any idea to fix this problem for Web Api???