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.
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);
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.