0

I have .pptx files in one location which I need to need to download in client system where ever user want to save or default browser download location.

Controller Code

var fileName = "textFile20210323.pptx";
var filePath = @"\\Depts\IT\TestFolder\";
var fileNamewithPath = $"{filePath}{fileName}";

Response.ClearHeaders();
Response.Clear();
Response.ContentType = "application/x-mspowerpoint";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileNamewithPath);
Response.WriteFile(fileNamewithPath);
Response.Flush();

return Json(new { success = "success" }, JsonRequestBehavior.AllowGet);

Script

    function DownloadFile(args) {
    $.ajax({
        type: "POST",
        url: "../Home/DownloadFile",
        data: { "json": JSON.stringify(args) },
        dataType: "json",
        beforeSend: function () {
        },
        success: function (data) {

            alert("Success");
        }
    });
}

Any other approach is acceptable.

Rocky
  • 4,454
  • 14
  • 64
  • 119
  • 1
    Why not simply return `File()` rather than going down the ajax route? Also check [This](https://stackoverflow.com/questions/5826649/returning-a-file-to-view-download-in-asp-net-mvc) question which should provide some more details – Izzy Mar 23 '21 at 15:39

2 Answers2

0

As mentioned, the simple approach is to not use Ajax at all for this. The following gives the user a link to download the file to their local computer.

View:

<a href="@Url.Action("GetFile", new { controller = "Home", path = @"\\Depts\IT\TestFolder\textFile20210323.pptx" })">Download File</a>

Controller:

using System.IO;

public FilePathResult GetFile(string path)
{
    string fileName = Path.GetFileName(path);
    return File(path, "application/octet-stream", fileName);
}
Tawab Wakil
  • 1,737
  • 18
  • 33
0

Controller.cs

    public FileResult DownloadFile(string FilePath, string FileName)
    {
        if (!string.IsNullOrEmpty(FilePath) && !string.IsNullOrEmpty(FileName))
        {
            return File(FilePath, "application/vnd.ms-powerpoint", FileName);
        }
        else
        {
            return null;
        }

    }

View.cshtml

 <a onClick="DownloadFile(this)">Download</a>

Script.js

    function DownloadFile(args) {
        window.location.href = "../Home/DownloadFile?FilePath=" + args.FilePath + "&FileName=" + args.Name;
    }
Rocky
  • 4,454
  • 14
  • 64
  • 119