Подтвердить что ты не робот

Как загрузить файл через ajax-запрос в asp.net MVC 4

Ниже мой код:

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

Это script, который я использую

$(function () {
    $("#DownloadAttachment").click(function () {
        $.ajax({
            url: '@Url.Action("DownloadAttachment", "PostDetail")',
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            type: "GET",
            success: function () {
                alert("sucess");
            }
        });    
    });
});      

Как вернуть файл для загрузки под над кодом?

4b9b3361

Ответ 1

Пожалуйста, попробуйте это с успехом 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 })';
                }
            });

        });
    });

Ответ 2

Я думаю, что нет необходимости в вызове Ajax, который вы можете сделать, просто используя гиперссылку, как показано ниже.

Просмотр кода

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

Метод контроллера

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

Ниже метод поможет вызывать действие из запроса Ajax из диалогового окна jQuery, и он выполняет действие и может быть закрыто диалоговое окно, как только действие вернет результат успеха

контроллер

    [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

$(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");
                }
            });

        });
});

Пожалуйста, обратитесь ко мне, если вам нужна дополнительная информация.

Ответ 4

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

    });
});

Ответ 5

Следующий код поможет вам создать файл pdf/excel на сервере и разрешить загрузку в браузере через вызов ajax.

Контроллер для создания файла 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});
    }

Следующий код контроллера позволит загрузить созданный файл из одного вызова 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];
    }

Используйте приведенный ниже вызов 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();
            });