0

I'm trying to download an image via ajaxusing <a>. This is my code to populate my 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.");
    }
})

Here is the code for the fncDownloadImage function:

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

And the code to the /Capability/Download Controller:

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

When I execute the fncDownloadImage the controller doesn't return an error but the fncDownloadImage function returns an error: SyntaxError: Unexpected token in JSON at position 0.

What is the problem with my code?

Odie
  • 375
  • 4
  • 16
  • You're telling the AJAX operation to expect JSON: `dataType: 'json'` An image is not JSON. But while that may correct the error, it may not get you any closer to your goal. What is it you're looking to do with the downloaded "file"? Currently all your callback does is `alert("Success");` – David Jun 14 '19 at 16:40
  • @David I want to download the file to my computer. What should the `dataType` be? – Odie Jun 14 '19 at 16:42

0 Answers0