Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Duncan Turner 32 posts 135 karma points
    Feb 18, 2021 @ 10:51
    Duncan Turner
    0

    Return a file from Umbraco Api Controller

    I have a file (docx) residing on my local machine and want it to be presented back to the user, I have this working for a typical MVC project but unfortunately not in an umbraco project.

    Umbraco Code as follows:

    public class MyDocxController : UmbracoApiController{
    private readonly string FileName = @"demo.docx";
    [System.Web.Http.HttpPost]
        public FileResult GetFile([System.Web.Http.FromBody] string json)
        {
            var _file = Path.GetFullPath(FileName);
            var _contentType = MimeMapping.GetMimeMapping(FileName);
            return new FilePathResult(_file, _contentType)
            {
                FileDownloadName = FileName
            };
        }}
    
  • Joep 96 posts 698 karma points
    Feb 18, 2021 @ 12:39
  • Mehmet Avcı 55 posts 240 karma points
    Feb 18, 2021 @ 14:03
    Mehmet Avcı
    0

    Hi,

    At base, since you are using UmbracoApiController., you are not using System.Net.Mvc namespace at first place.

    ApiController is deriven over ControllerBase not the Controller class. Controller is also deriven over ControllerBase and contains view support (and all fancy results classes).

    When you have ApiController, I suggest you to use HttpResponseMessage and deliver your file as data.

    Below I added a stackoverflow link you might want to check out.

    https://stackoverflow.com/questions/26038856/how-to-return-a-file-filecontentresult-in-asp-net-webapi

    -Mehmet

  • Duncan Turner 32 posts 135 karma points
    Feb 19, 2021 @ 12:10
    Duncan Turner
    0

    Thanks for replying, I tried using the HttpResponseMessage in a class and call it through the Controller: UmbracoApiController, it steps through ok but I am never presented with the document.

    HttpResponseMessage

      public HttpResponseMessage Build()
        {
    
            var path = HttpContext.Current.Server.MapPath("~/Downloads/" + FileName);
    
            var dataBytes = File.ReadAllBytes(path);
            var dataStream = new MemoryStream(dataBytes);
            var result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            result.Content = new StreamContent(dataStream);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = Path.GetFileName(path)
            };
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
    
            return result;
    
  • Mehmet Avcı 55 posts 240 karma points
    Feb 19, 2021 @ 12:28
    Mehmet Avcı
    0

    Hi Duncan,

    Your code looked quite solid to me, so I copied it over to test on my side. I got the file right away.

    Do you think it is related to how you have called it?

  • Duncan Turner 32 posts 135 karma points
    Feb 19, 2021 @ 12:53
    Duncan Turner
    0

    No way!

    I am using angular to send a post request to the controller: UmbracoApiController then calls the class file.

            var endPoint = "/Umbraco/Api/WordDocX/Post";
        $http.post(endPoint, "=" + jsonData, config)....etc
    

    What are you using to get the file?

    I will eventually build on this but wanted to prove that I could serve the document first.

  • Mehmet Avcı 55 posts 240 karma points
    Feb 19, 2021 @ 12:57
    Mehmet Avcı
    0

    Hi again,

    Well, I picked the simplest plain way, direct call over browser.

    Edit: I would love to hear about how this is handled with angular, not really my area.

  • Duncan Turner 32 posts 135 karma points
    Feb 19, 2021 @ 13:05
    Duncan Turner
    0

    so for me;

    I use angular to call the controller which in turn returns the HttpResponseMessage class.

    Why it is not serving the document I have no idea.

    It is promising that you are getting the file though! Thanks for trying that out for me!

  • Duncan Turner 32 posts 135 karma points
    Feb 26, 2021 @ 14:25
    Duncan Turner
    1

    So finally got this to work. It was indeed the way I was calling it being the issue, this is what I now have and is serving the document;

    var Config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            responseType: 'arraybuffer'
        }
    
        $http.post(EndPoint, "=" + jsonData, Config)
            .then(function (response) {
    
                var File = new Blob([response.data], { type: 'application/vnd.ms-word' });
                var FileURL = URL.createObjectURL(File);
                var Filename = 'MyDocument.docx';
    
                if (detectIE()) {
                    return window.navigator.msSaveOrOpenBlob(File, Filename);
                }
    
                var a = document.createElement('a');
                a.href = FileURL;
                a.Target = '_blank';
                a.download = Filename;
                document.body.appendChild(a);
                a.click();
    
            }, function (error) {
                alert("Cannot write out Word Document, sorry!");
                console.log(error);
            });
    

    Hope it helps someone!

Please Sign in or register to post replies

Write your reply to:

Draft