Copied to clipboard

Flag this post as spam?

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


  • Niels Lynggaard 190 posts 548 karma points
    Aug 30, 2018 @ 09:47
    Niels Lynggaard
    0

    Create a SurfaceController Action to zip some files and return them..

    Hi All.

    I'm working on a solution to combine a few files into a .zip and return it to the browser.

    I'm looking to use the included zip-library ICSharpCode.SharpZipLib.Zip;

    Any chance someone has an example of this? What kind of result should my action return?

    Cheers, Niels

  • Nik 1591 posts 7148 karma points MVP 6x c-trib
    Aug 30, 2018 @ 15:06
    Nik
    0

    Hi Niels,

    There are a few bits an pieces to consider, but basically you need to return the File, however there are a couple of different ways of doing this.

    You can return a FilePathResult, as demonstrated here: https://www.c-sharpcorner.com/UploadFile/db2972/file-result-in-controller-sample-in-mvc-day-15/

    You can also return a FileStreamResult discussed in the question here: https://stackoverflow.com/questions/5826649/returning-a-file-to-view-download-in-asp-net-mvc

    Or you can roll your own HttpResponseMessage as demonstrated here: https://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api

    There is also a FileContentResult which I couldn't find an example of quickly (sorry)

    Each approach has different benefits and I think in the past I've generally used a FileContentResult to return files from controllers.

    Cheers

    Nik

  • Niels Lynggaard 190 posts 548 karma points
    Sep 18, 2018 @ 13:36
    Niels Lynggaard
    0

    Thanx for your input, Nik!

    I ended up using a FileContentResult like this;

    return (ActionResult)this.File(this.GetFile(this.Server.MapPath("/zip/" + (object)productPageID + "datasheets.zip")), "application/octet-stream", "datasheets.zip");
    

    the GetFile method returns a byte-array like this;

    private byte[] GetFile(string s)
        {
            FileStream fileStream = System.IO.File.OpenRead(s);
            byte[] buffer = new byte[fileStream.Length];
            if ((long)fileStream.Read(buffer, 0, buffer.Length) != fileStream.Length)
                throw new IOException(s);
            return buffer;
        }
    

    This works like a charm :)

Please Sign in or register to post replies

Write your reply to:

Draft