gpt4 book ai didi

c# - 使用 Ajax 和 iframe 下载文件

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:29 24 4
gpt4 key购买 nike

我读过有关使用 Ajax 和 iframe 进行文件下载的内容。任何人都可以逐步解释如何执行此操作或了解任何教程,因为我们已经在该项目上使用了 ajax,这似乎是执行此操作的最佳方法。

编辑:

好的,这是我的 View 代码:

<div class="buttons">
<input type="button" value="Download File" class="button" id="downloadfile">

<script type="text/javascript">
$(function () {
$('#downloadfile').click(function (e) {
$('#downloadIframe').attr('src', '@Url.Action("DownloadFile","Invoice")' + '/Report/Invoices');
});
});
</script>

这是我的 Controller :

public FileResult DownloadFile(int id)
{

byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Reports/Invoices/" + Table.First(x => x.ID == id).ID + ".pdf"));
string fileName = Table.First(x => x.ID == id).ID.ToString();
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
}

public ActionResult Download(int id)
{
return AjaxResponse("Download", null);
}

我有一个 Jquery 上下文菜单,我用它点击 JQGrid 中的一行,然后打开 View Download 然后在我单击按钮的 View ,它应该在 View 中执行 script 并在 Controller 中返回 DownloadFile FileResult 但是当我单击按钮。

报告所在的文件夹:~/Reports/Invoices

最佳答案

我不知道 iframe,但我通过 ajax 下载文件的方式只是简单地写入响应流。

    [HttpGet]
[OutputCache(VaryByCustom="id")]
public void DownloadFile(int id)
{
var path = GetFilePath(id);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=xxx");
Response.WriteFile(path);
Response.End();
}

关于c# - 使用 Ajax 和 iframe 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21596950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com