Я пытаюсь загрузить файл с локального сервера. Метод, который загружает файл, отображает сообщение об ошибке, если файл не может быть найден.
Это код на мой взгляд:
function download(id) {
var response = null;
var fileId = id == null? 0 : id;
var args = {fileId : fileId };
$.ajax({
type: 'POST',
url: '/Home/DownloadFile',
data: args,
dataType: "json",
traditional: true,
success: function (data) {
$("#message").attr('style', 'margin-left:auto; margin-right:auto; font- weight: bold; color: Red');
$("#message").html(data.message);
}
});
}
}
<div id="message"></div>
<a class="fileName" href="javascript:void(0)" onclick='download(@f.Id)'>@f.Name</a>
А это мой контроллер:
public JsonResult DownloadFile(int fileId)
{
FileService fileService = new FileService();
DirectoryService directoryService = new DirectoryService();
File file = fileService.GetByFileId(fileId);
bool noError = false;
string _message = String.Empty;
if (file == null)
{
_message = "File does not exist";
}
else if (System.IO.File.Exists(file.FilePath))
{
using (StreamReader reader = System.IO.File.OpenText(file.FilePath))
{
Stream s = reader.BaseStream;
byte[] fileData = Utils.ReadStream(s);
string contentType = Utils.getContentType(file.FileName);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment;filename=" + file.FileName);
Response.ContentType = contentType;
Response.BinaryWrite(fileData);
noError = true;
}
}
else
{
_message = "File \"" + file.FileName + "\" could not be found."; //File "foo.txt" could not be found
}
if (noError)
_message = String.Empty;
var data = new { message = _message };
return Json(data, JsonRequestBehavior.AllowGet);
}
Странно то, что когда я впервые это проверил, это сработало. Я не помню, чтобы что-то менялось, но теперь метод выполняется нормально, но файл не скачивается. Кто-нибудь может мне помочь, пожалуйста?