我正在尝试使用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
。
我的代码有什么问题?