Mehul Patel
Mehul Patel

Reputation: 1204

MVC 4 File Download

Here is my code I tried following way to put functionality for download a file but it doesn't work properly. It doesn't show save file dialog.

 protected virtual FileResult Download(string FileName, string FilePath)
 {

        Response.AppendHeader("Content-Length", FileName.Length.ToString());
        return File(FilePath, "application/exe", FileName);
 }

And tried this way also:

protected virtual ActionResult Download(string FileName, string FilePath)
{
    Response.Clear();
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
    Response.AppendHeader("Content-Length", FileName.Length.ToString());
    Response.ContentType = "application//x-unknown";
    Response.WriteFile(FilePath.Replace("\\", "/"));
     Response.Flush();
    Response.End(); 
}

But both are not working. What I missing?

Upvotes: 4

Views: 4890

Answers (2)

Mehul Patel
Mehul Patel

Reputation: 1204

I don't know major difference but following code is working fine for me for any file..May be because of ContentType as per @Garath suggest.

var fileInfo = new System.IO.FileInfo(oFullPath);
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", yourfilename));
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.WriteFile(oFullPath);
            Response.End();

Upvotes: 4

Piotr Stapp
Piotr Stapp

Reputation: 19828

The correct mimitype for exe file is application/octet-stream not application/exe or application//x-unknown - check MSDN You could look here for more definitions: Get MIME type from filename extension

Upvotes: 2

Related Questions