Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File downloads in a self-host Nancy application

Tags:

nancy

I'm working on a small project that uses Nancy hosted from within a WPF application. I want to be able to remotely download a PDF file that is ~8MB. I was able to get the download to work but while the download is in progress the application won't respond to any other requests. Is there a way I can allow the file download without tying up the all other requests?

Public Class ManualsModule : Inherits NancyModule
    Public Sub New()
        MyBase.New("/Manuals")

        Me.Get("/") = Function(p)
            Dim model As New List(Of String) From {"electrical", "opmaint", "parts"}
            Return View("Manuals", model)
        End Function

        Me.Get("/{name}") = Function(p)
            Dim manualName = p.name
            Dim fileResponse As New GenericFileResponse(String.Format("Content\Manuals\{0}.pdf", manualName))
            Return fileResponse
        End Function
    End Sub
End Class

Or in C#

public class ManualsModule : NancyModule
{
    public ManualsModule() : base("/Manuals")
    {
        this.Get("/") = p =>
        {
            List<string> model = new List<string> {
                "electrical",
                "opmaint",
                "parts"
            };

            return View("Manuals", model);
        };

        this.Get("/{name}") = p =>
        {
            dynamic manualName = p.name;
            GenericFileResponse fileResponse = new GenericFileResponse(string.Format("Content\\Manuals\\{0}.pdf", manualName));
            return fileResponse;
        };
    }
}
like image 737
jweaver Avatar asked Nov 21 '13 13:11

jweaver


3 Answers

var file = new FileStream(zipPath, FileMode.Open);
string fileName = //set a filename

var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName));
return response.AsAttachment(fileName);
like image 81
Mohit Verma Avatar answered Oct 19 '22 18:10

Mohit Verma


The easiest way is to create a StreamWriter around it, like this:

var response = new Response();

response.Headers.Add("Content-Disposition", "attachment; filename=test.txt");
response.ContentType = "text/plain";
response.Contents = stream => {
    using (var writer = new StreamWriter(stream))
    {
        writer.Write("Hello");
    }
};

return response;
like image 41
Alex Daniel Lewis Avatar answered Oct 19 '22 16:10

Alex Daniel Lewis


I found that I was actually hosting Nancy in WCF not self-host. The behaviour I described only happens when hosted in WCF. Self-Host will work fine for my application so I'll go with that.

like image 3
jweaver Avatar answered Oct 19 '22 18:10

jweaver