如何在asp.net MVC 4中通过ajax请求下载文件 [英] How to download a file through ajax request in asp.net MVC 4

查看:41
本文介绍了如何在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");
            }
        });    
    });
});      

以上代码如何返回下载文件?

How to return the file for download pursing above code?

推荐答案

请在 ajax 中试试这个成功

Please, try this in ajax success

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请求下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆