I'm trying to download an image via ajax
using <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?