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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30704078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:43:31  来源:igfitidea点击:

How to download a file through ajax request in asp.net MVC 4

jqueryjsonasp.net-mvc-4asp.net-ajax

提问by rohit singh

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?

如何返回用于下载上述代码的文件?

采纳答案by Edin Mahmutovi?

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

        });
    });

回答by Govinda Rajbhar

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

回答by Mahesh ML

The following code will help you to create the pdf/excel file in server and allow to download in browser through ajax call.

以下代码将帮助您在服务器中创建 pdf/excel 文件,并允许通过 ajax 调用在浏览器中下载。

Controllerfor creating the pdf/excel file

用于创建 pdf/excel 文件的控制器

public async Task<JsonResult> CardStatusReportExport(ReportFilterInputModel cardStatusReportInputModel, string type, string sortOrder)
    {
        cardStatusReportInputModel.ReportType = Reprot_Type_Const.CardStatus;
        cardStatusReportInputModel.ReportFormat = type;

        var CardStatusReport = await _reportDocGeneration.DocGeneartion(cardStatusReportInputModel);
        string result = Path.GetTempPath();
        string fileName = "CardStatusReport" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
        if (type.Equals(Constants.FILE_TYPE_PDF))
        {
            fileName = fileName + Constants.FILE_EXTENSION_PDF;
            System.IO.File.WriteAllBytes(result + fileName, CardStatusReport);
        }
        else
        {
            fileName = fileName + Constants.FILE_EXTENSION_EXCEL;
            System.IO.File.WriteAllBytes(result + fileName, CardStatusReport);
        }
        return Json(new { fileName = fileName});
    }

The following controller code will allow to download the created file from a single ajax call

以下控制器代码将允许从单个 ajax 调用下载创建的文件

[HttpGet]    
    public async Task<ActionResult> Download(string file)
    {
        var path = Path.Combine(Path.GetTempPath(),file);
        var memory = new MemoryStream();
        try
        {
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
        }
        catch (Exception e)
        {
            ModelState.AddModelError("FileNotFoundError", e.Message);
            return Content(e.Message);
        }
        memory.Position = 0;
        return File(memory, GetContentType(path), Path.GetFileName(path));
    }

    private string GetContentType(string path)
    {
        var types = MediaType.GetMimeTypes();
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return types[ext];
    }

Use the below ajaxcall for creation of pdf/excel file and download the same.

使用下面的ajax调用创建 pdf/excel 文件并下载相同的文件。

$.ajax({
                method: 'POST',
                data: { type: val, cardStatusReportInputModel: payload, sortOrder : sortOrder},
                url: '@Url.Action("CardStatusReportExport", "Reports")'
            }).done(function (data, statusText, xhdr) {
                try {
                    if (data.fileName != "") {
                        window.location.href = "@Url.RouteUrl(new { Controller = "Reports", Action = "Download"})/?file=" + data.fileName;
                        ShowMessageAlert('@Html.Raw(Localizer["Report has been exported successfully"].Value.ToString())');
                    }
                    $("#divLoader").hide();
                }
                catch (e) {
                    $("#divLoader").hide();
                }
            }).fail(function (xhdr, statusText, errorText) {
                alert('error');
                $("#divLoader").hide();
            });

回答by Dilshad

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

    });
});

回答by Mohanavelu K

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.

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