使用ASP.NET Razor Pages,我正在尝试将文件下载到浏览器。 从页面(html),使用这样的链接工作正常:
href="/DownloadableFiles/testB.csv" download="newname">Download Link
但是,我想从代码隐藏或ViewModel
开始下载,因此它可以是动态的文件名,我还需要先检查文件等等。
在ASP.NET MVC核心(不是RazorPages)中,您可以使用以下代码下载文件:
return File(memory, GetContentType(path), Path.GetFileName(path));
但Razor Pages不支持return File
。
答案 0 :(得分:3)
pitaridis是正确的,Razor Pages中存在return File
,我一定错过了命名空间。
这将从Code Behind下载文件:
在页面中,这是提交按钮:
<button type="submit" asp-page-handler="DownloadFile" style="width:75px"
class="cancel"> Download </button>
在PageModel(代码隐藏)中:
public ActionResult OnPostDownloadFile()
{
return File("/DownloadableFiles/TestFile34.csv", "application/octet-stream",
"NewName34.csv");
}
注意: / DownloadableFiles是wwwroot的子目录。
答案 1 :(得分:2)
也可以像这样使用 GET 调用代替 POST:
把这个放在你的页面代码后面:
public void getFrames(char **data, size_t *datasize) {
std::string s = getFramesAsString();
size_t size = s.length();
char *c = new char[size];
s.copy(c, size, 0);
*datasize = size;
*data = c;
};
public void putFrame(char *data, size_t datasize) {
const std::lock_guard<std::mutex> lock(frames_mtx);
frames.push_front(std::string(data, datasize));
};
并将其放在该页面上:
public ActionResult OnGetDownload()
{
return File("c:/Directory/FileName.csv", "application/octet-stream", "FileName.csv");
}
如果您想传递参数,只需将它们包含在 Url.Page 调用中,并像这样将参数添加到 OnGetDownload:
<a href="@Url.Page("ThePageName", "Download")>Download</a>