c# - 如何从一个文件夹下载 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");
}
});
}
任何其他方法都是可以接受的。
解决方案
如前所述,简单的方法是根本不使用 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);
}
推荐阅读
- android - 如何让 android:hyphenationFrequency 工作
- postgresql - 使用 bkp.tar.gz 文件恢复 postgreSQL 备份
- r - R中posixlt之间的循环
- c - 线程竞争条件和 C 中的值传递
- python - 如何循环一个scrapy脚本?
- android - 无法解决Android中发生的GoogleMap错误
- javascript - 如何使用 Javascript 对表格行进行排序
- java - JUnit 4.11 -> 4.12 引入了@Rule 错误,不执行测试
- c++ - 不能在没有对象的情况下调用成员函数(尽管我相信我确实初始化了它)
- python - 如何找出函数是否已由 `lambda` 或 `def` 声明?