如何通过asp.net MVC 4中的ajax请求下载文件
下面是我的代码:
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
success: function () {    window.location = '@Url.Action("DownloadAttachment", "PostDetail")';
}
更新的答案:
public ActionResult DownloadAttachment(int studentId){          
    // Find user by passed id
    // Student student = db.Students.FirstOrDefault(s => s.Id == studentId);
    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);
}
Ajax请求:
$(function () {        $("#DownloadAttachment").click(function () {
            $.ajax(
            {
                url: '@Url.Action("DownloadAttachment", "PostDetail")',
                contentType: 'application/json; charset=utf-8',
                datatype: 'json',
                data: {
                    studentId: 123
                },
                type: "GET",
                success: function () {
                    window.location = '@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })';
                }
            });
        });
    });
以上是 如何通过asp.net MVC 4中的ajax请求下载文件 的全部内容, 来源链接: utcz.com/qa/422339.html







