下面是我的代码:
ActionResult DownloadAttachment(student st)
{
var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == st.Lisaid);
byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);
}
这是我正在使用的脚本
$(function () {
$("#DownloadAttachment").click(function () {
$.ajax({
url: '@Url.Action("DownloadAttachment", "PostDetail")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
type: "GET",
success: function () {
alert("sucess");
}
});
});
});
如何返回上述代码的下载文件?
最佳答案
我认为不需要 Ajax 调用,您只需使用超链接即可完成,如下例所示。
查看代码
<a href="@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })">Download Form</a>
Controller 方法
public ActionResult DownloadAttachment(int studentId)
{
// Find user by passed id
var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);
byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);
}
关于jquery - 如何在asp.net MVC 4中通过ajax请求下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30704078/