通过AJAX调用Controller时返回文件不起作用

时间:2019-06-14 16:36:29

标签: javascript ajax asp.net-mvc asp.net-ajax

我正在尝试使用ajax通过<a>下载图像。这是我的代码,用于填充我的DataTable

$.ajax({
    url: "/Capability/GetAllTrainingLog",
    type: "GET",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $("#tblTrainingLog").dataTable({
            data: data,
            columns: [
            {'data' : 'TrainingTitle'},
            {'data' : 'TrainingURL'},
            {"data": null, render: function (data, type, row) {
                //data.attachment returns a file path e.g C:\Project\App_Data\image.jpg
                return '<a onclick="fncDownloadImage(\''+ data.Attachment.replace(/\\/g,"\\\\") +'\')" >Download</a>'
            }}
        }
        ]
    });
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("A problem has been encountered. Please contact the web administrator.");
    }
})

以下是fncDownloadImage函数的代码:

function fncDownloadImage(fileName)
{
        var download = {'filePath' : fileName}
        $.ajax({
        type: "POST",
        url: '/Capability/Download',
        data: JSON.stringify(download),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            alert('Success');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

以及/Capability/Download控制器的代码:

[HttpPost]
public FileResult Download(TrainingModel pass)
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(pass.filePath);
    string fileName = Path.GetFileName(pass.filePath);
    return File(pass.filePath, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(pass.filePath));
}

当我执行fncDownloadImage时,控制器不会返回错误,但是fncDownloadImage函数会返回错误:SyntaxError: Unexpected token in JSON at position 0

我的代码有什么问题?

0 个答案:

没有答案