1

I want to make ability to download attachments from my site, (I need to make it runs in IE) so in html I have:

<a href="api/attachments/DownloaAttachment?id={{attachment.Id}}" target="_blank">
   Download Image
</a>
<!-- {{attachment.Id}} - it's because I use AngularJS  :)  -->

in controller:

        [HttpGet]
        public FileContentResult DownloaAttachment(int id)
        {
            var att = GetAttachmentById(id);
            byte[] fileBytes = att.Content.Content;
            var response = new FileContentResult(fileBytes, MediaTypeNames.Application.Octet);
            response.FileDownloadName = att.FileName;
            return response;
        }

but when I click on "Download Image" - I have a new window and responce from controller as json, like:

{"FileContents":"/9j/4.. some bytes..ZK9k=","ContentType":"application/octet-stream","FileDownloadName":"Cover.jpg"}

But I don't need that JSON, I need to be able to download attach as file to user's computer. How can I make it as simple file download? What am I do wrong?

paulpeters
  • 158
  • 8

3 Answers3

0

Try changing this line:

var response = new FileContentResult(fileBytes, MediaTypeNames.Application.Octet);

to:

var response = new FileContentResult(fileBytes, "image/jpeg");
Jeroen Vannevel
  • 41,258
  • 21
  • 92
  • 157
Tyler Day
  • 1,640
  • 11
  • 12
  • I try to change as you wrote, but there is nothing changes. - Opens new window and I see {"FileContents":"/9j/4AAQSkZJRg...bla..bla..Afbs//Z","ContentType":"image/jpeg","FileDownloadName":"CoverBack.JPG"} right on a page.. – paulpeters Nov 09 '14 at 12:15
0

Hope you have tried - Returning binary file from controller in ASP.NET Web API.

It says return HttpResponseMessage and set Content of response = file content and set header content type.

Also, i would suggest to look into this - Download file from an ASP.NET Web API method using AngularJS.

It says, you also need to set Content.Headers.ContentDisposition and Content.Headers.ContentDisposition.FileName .

Community
  • 1
  • 1
Arindam Nayak
  • 7,138
  • 4
  • 28
  • 45
0

Hope this works.

    [HttpGet]
    public HttpResponseMessage DownloaAttachment(int id)
    {
        var att = GetAttachmentById(id);
        byte[] fileBytes = att.Content.Content;
        var response = new FileContentResult(fileBytes, MediaTypeNames.Application.Octet);
        response.FileDownloadName = att.FileName;
        return Request.CreateResponse(HttpStatusCode.OK, response, new MediaTypeHeaderValue("image/*"));

    }

or if you have file extension pass on that instead of * in (image/*).

refer: MSDN

Kalyan
  • 175
  • 1
  • 12