简体   繁体   中英

Download file from DB with ajax call MVC

I'm trying to implement file download functionality thru ajax call in MVC. After calling of controller method i always have a "parseerror", can somebody explain me why?

my ajax:

tab.on("click", ".FileDownload", function (e) {

    //$('#uploadStatus').html("ok");
    var tr = $(this).closest("tr");
    var id = tr.data("id");

    $.ajax({
        type: "POST",
        url: "/File/FileDownload",
        //contentType: false,
        //processData: false,
        //dataType: "json",
        data: { fileId: id },
        success: function (data) {
            $('#uploadStatus').html("ok");
        },
        error: function (err) {
            alert(err.statusText);
        }
    });

});

and controller:

[HttpPost]
    public FileResult FileDownload(int? fileId)
    {

        FileDBEntities db = new FileDBEntities();
        tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
        return File(file.Data, file.ContentType, file.Name);
    }

with simple download link in razor it works, but not with ajax. What am I doing wrong here?

Why not simple use

tab.on("click", ".FileDownload", function (e) {

    //$('#uploadStatus').html("ok");
    var tr = $(this).closest("tr");
    var id = tr.data("id");

    window.location = window.location.origin + '/File/FileDownload?fileId=' + id;

});

[HttpGet]
    public FileResult FileDownload(int? fileId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM