Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from controller

In an Aspnet5 RC1 update1 web application, I am trying to do the same as Response.BinaryWrite, file download in old AspNet application.

The user needs to get a popup save dialog in client side.

When the following code is used, a popup prompt appears in client side to save the file:

public void Configure(IApplicationBuilder app)
{
    //app.UseIISPlatformHandler();
    //app.UseStaticFiles();
    //app.UseMvc();
    app.Run(async (objContext) =>
    {
        var cd = new System.Net.Mime.ContentDisposition { 
                     FileName = "test.rar", Inline = false };
        objContext.Response.Headers.Add("Content-Disposition", cd.ToString());
        byte[] arr = System.IO.File.ReadAllBytes("G:\\test.rar");
        await objContext.Response.Body.WriteAsync(arr, 0, arr.Length);
    });
}

But when the same code is used inside a Controller's action, app.Run is commented out, the save popup does not appear, the content is just rendered as text.

[Route("[controller]")]
public class SampleController : Controller
{
    [HttpPost("DownloadFile")]
    public void DownloadFile(string strData)
    {
        var cd = new System.Net.Mime.ContentDisposition { 
                     FileName = "test.rar", Inline = false };                
        Response.Headers.Add("Content-Disposition", cd.ToString());
        byte[] arr = System.IO.File.ReadAllBytes("G:\\test.rar");                
        Response.Body.WriteAsync(arr, 0, arr.Length);  

Control flow needs to come to controller, perform some logic, then send byte[] response content to client side, then the user needs to save the file. There is no cshtml, just plain html with jquery ajax call.

like image 435
Navaneeth Avatar asked Jan 05 '16 06:01

Navaneeth


1 Answers

Do you really need HttpPost attribute? Try to remove it or to use HttpGet instead:

public async void DownloadFile()
{
    Response.Headers.Add("content-disposition", "attachment; filename=test.rar");
    byte[] arr = System.IO.File.ReadAllBytes(@"G:\test.rar");
    await Response.Body.WriteAsync(arr, 0, arr.Length);
}

UPDATED: Probably more easy would be the usage of FileStreamResult:

[HttpGet]
public FileStreamResult DownloadFile() {
    Response.Headers.Add("content-disposition", "attachment; filename=test.rar");
    return File(new FileStream(@"G:\test.rar", FileMode.Open),
                "application/octet-stream"); // or "application/x-rar-compressed"
}
like image 195
Oleg Avatar answered Nov 12 '22 21:11

Oleg