如何通过asp.net MVC 4中的ajax请求下载文件

时间:2022-12-04 17:20:40

Below is my code :

以下是我的代码:

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);                 
}

This is the script which i'm using

这是我正在使用的脚本

$(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?

如何返回文件下载追求上面的代码?

4 个解决方案

#1


6  

Please, try this in ajax success

请在ajax成功中试试这个

success: function () {
    window.location = '@Url.Action("DownloadAttachment", "PostDetail")';
}

Updated answer:

更新的答案:

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 request:

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 })';
                }
            });

        });
    });

#2


3  

I think there is no need of Ajax call you can do simply using hyperlink as below example.

我认为不需要Ajax调用你可以简单地使用超链接,如下例所示。

View Code

查看代码

<a href="@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })">Download Form</a>

Controller Method

控制器方法

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);                           
}

#3


0  

Below method would helps calling action from Ajax request from jQuery dialog window and it executes the action and can be closed dialog window as soon the action return success result

下面的方法将有助于从jQuery对话框窗口调用Ajax请求中的操作并执行操作,并且可以在操作返回成功结果后立即关闭对话框窗口

Controller

调节器

    [HttpGet]
    public ActionResult DownloadCampaign(string filePath, string mode)
    {
        string contentType = string.Empty;
        var sDocument = filePath;
        if (!System.IO.File.Exists(sDocument))
        {
            return HttpNotFound();
        }

        if (mode == "action")
            return Json(new {fileName = filePath}, JsonRequestBehavior.AllowGet);

        if (sDocument.Contains(".pdf"))
        {
            contentType = "application/pdf";
        }
        else if (sDocument.Contains(".docx"))
        {
            contentType = "application/docx";
        }
        else if (sDocument.Contains(".xls"))
        {
            contentType = "application/xlsx";
        }

        return File(sDocument, contentType, sDocument);
    }

JQuery - Ajax Request

JQuery - Ajax请求

$(document)
    .ready(function() {
        $("#btnDownload").click(function () {
            var file = $("#FilePath").val();
            $.ajax({
                url: '@Url.Action("DownloadCampaign", "FileList")',
                data: { filePath: file, mode:'action' },
                method: 'GET',
                dataType: 'json',
                //contentType: 'application/json; charset=utf-8',

                success: function(data) {
                    @*window.location = '@Url.RouteUrl("DownloadCampaign", "FileList", new { filePath = data1.fileName })';*@
                    window.location.href = "@Url.RouteUrl(new
                    { Controller = "FileList", Action = "DownloadCampaign" })/?filePath=" + data.fileName + "&mode=download";
                    $("#downloadFile_dialog").dialog("close");
                },
                error: function (req, status, errorObj) {
                    alert("Error");
                }
            });

        });
});

Please reach out to me if you need more information about this.

如果您需要更多相关信息,请与我联系。

#4


0  

public FileResult DownloadGeneralDocs(string docName)
    {
        string fileName = docName+".pdf";           
        var path = _globalWebSettings.Value.DownloadGeneralDocsPath;
        string filePath = "";
        if (fileName!="")
        {
            filePath = (_env.WebRootPath + string.Format("{0}{1}",path, fileName));
        }
        FileInfo file1 = new FileInfo(filePath);            
        byte[] fileBytes = System.IO.File.ReadAllBytes(file1.FullName);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);            
    }

view.cshtml:
<script>
$(document).ready(function () {
    $("#docTable tbody tr td button").click(function (e) {
        var docName = $(this).closest("tr").find(".document_td_data").text();
        $.ajax({
            url: '@Url.Action("DownloadGeneralDocs", "Documents")',                    
                dataType: "html",
                cache:false,
                data: { 'docName': docName },
                success: function (data) {                     
                    window.location.href = "@Url.RouteUrl(new
                { Controller = "Documents", Action = "DownloadGeneralDocs" })/?docName=" + docName ;

                },
                error: function (err, response) {
                    console.log(err, response);
                    alert(err, response.responseText);
                }
            })

    });
});

#1


6  

Please, try this in ajax success

请在ajax成功中试试这个

success: function () {
    window.location = '@Url.Action("DownloadAttachment", "PostDetail")';
}

Updated answer:

更新的答案:

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 request:

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 })';
                }
            });

        });
    });

#2


3  

I think there is no need of Ajax call you can do simply using hyperlink as below example.

我认为不需要Ajax调用你可以简单地使用超链接,如下例所示。

View Code

查看代码

<a href="@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })">Download Form</a>

Controller Method

控制器方法

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);                           
}

#3


0  

Below method would helps calling action from Ajax request from jQuery dialog window and it executes the action and can be closed dialog window as soon the action return success result

下面的方法将有助于从jQuery对话框窗口调用Ajax请求中的操作并执行操作,并且可以在操作返回成功结果后立即关闭对话框窗口

Controller

调节器

    [HttpGet]
    public ActionResult DownloadCampaign(string filePath, string mode)
    {
        string contentType = string.Empty;
        var sDocument = filePath;
        if (!System.IO.File.Exists(sDocument))
        {
            return HttpNotFound();
        }

        if (mode == "action")
            return Json(new {fileName = filePath}, JsonRequestBehavior.AllowGet);

        if (sDocument.Contains(".pdf"))
        {
            contentType = "application/pdf";
        }
        else if (sDocument.Contains(".docx"))
        {
            contentType = "application/docx";
        }
        else if (sDocument.Contains(".xls"))
        {
            contentType = "application/xlsx";
        }

        return File(sDocument, contentType, sDocument);
    }

JQuery - Ajax Request

JQuery - Ajax请求

$(document)
    .ready(function() {
        $("#btnDownload").click(function () {
            var file = $("#FilePath").val();
            $.ajax({
                url: '@Url.Action("DownloadCampaign", "FileList")',
                data: { filePath: file, mode:'action' },
                method: 'GET',
                dataType: 'json',
                //contentType: 'application/json; charset=utf-8',

                success: function(data) {
                    @*window.location = '@Url.RouteUrl("DownloadCampaign", "FileList", new { filePath = data1.fileName })';*@
                    window.location.href = "@Url.RouteUrl(new
                    { Controller = "FileList", Action = "DownloadCampaign" })/?filePath=" + data.fileName + "&mode=download";
                    $("#downloadFile_dialog").dialog("close");
                },
                error: function (req, status, errorObj) {
                    alert("Error");
                }
            });

        });
});

Please reach out to me if you need more information about this.

如果您需要更多相关信息,请与我联系。

#4


0  

public FileResult DownloadGeneralDocs(string docName)
    {
        string fileName = docName+".pdf";           
        var path = _globalWebSettings.Value.DownloadGeneralDocsPath;
        string filePath = "";
        if (fileName!="")
        {
            filePath = (_env.WebRootPath + string.Format("{0}{1}",path, fileName));
        }
        FileInfo file1 = new FileInfo(filePath);            
        byte[] fileBytes = System.IO.File.ReadAllBytes(file1.FullName);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);            
    }

view.cshtml:
<script>
$(document).ready(function () {
    $("#docTable tbody tr td button").click(function (e) {
        var docName = $(this).closest("tr").find(".document_td_data").text();
        $.ajax({
            url: '@Url.Action("DownloadGeneralDocs", "Documents")',                    
                dataType: "html",
                cache:false,
                data: { 'docName': docName },
                success: function (data) {                     
                    window.location.href = "@Url.RouteUrl(new
                { Controller = "Documents", Action = "DownloadGeneralDocs" })/?docName=" + docName ;

                },
                error: function (err, response) {
                    console.log(err, response);
                    alert(err, response.responseText);
                }
            })

    });
});