首页 > 解决方案 > 如何从一个文件夹下载 pptx 文件到客户端系统 - MVC

问题描述

我在一个位置有 .pptx 文件,我需要将其下载到用户想要保存的客户端系统或默认浏览器下载位置。

控制器代码

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);

脚本

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

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

任何其他方法都是可以接受的。

标签: c#asp.net-mvcdownload

解决方案


如前所述,简单的方法是根本不使用 Ajax。以下为用户提供了将文件下载到本地计算机的链接。

看法:

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

控制器:

using System.IO;

public FilePathResult GetFile(string path)
{
    string fileName = Path.GetFileName(path);
    return File(path, "application/octet-stream", fileName);
}

推荐阅读