Base solution for your next web application
Ends in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

File download from ApplicationService #5794


User avatar
0
josus created

Hi all,

I am using angular file saver to download a file from the server. My Application Service creates an image on the fly and return a byte array from a memory stream. On the client side, the data is received as string. The file saver get the data with a Blob object and it save the file to disk. But, when I try to open it it is wrong.

Can you provide some code sample with the correct way to do this? Is the ApplicationService the correct place to do it? I am using mvc5/angularjs version of aspnetzero.

Thanks in advance.

Josus


4 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @josus,

    If your project is MVC 5.x and AngularJS, you can check how we handle the profile image of the user.

  • User Avatar
    0
    josus created

    I saw it, but it is done in a MVC controller and the return type is a FileResult. I need to return the image data, something like a byte array from an ApplicationService, where no reference to System.Web.Mvc is needed. Any other option to make it work?

  • User Avatar
    1
    josus created

    I answer myself:

    My ApplicationService now returns a Dto with a byte[] for the image data and other additional properties. When this Dto is serialized as Json string the byte[] is converted to a Base64 string.

    In my controler I used this;

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from

    to convert back this Base64 string to a javascript byte array that is the source for a Blob passed to FileSaver module. And it works!!

    The final client code looks like this:

                    employeeService.getEmployeeCard(employee.id)
                        .then(function (result) {
                            var bytes = Uint8Array.from(atob(result.data.image), c => c.charCodeAt(0));
                            var data = new Blob([bytes], { type: 'image/jpeg' });
                            fileSaver.saveAs(data, result.data.employeeName + '.jpeg');
                        });
    

    Regards!

  • User Avatar
    0
    ismcagdas created
    Support Team

    @josus Thanks!