我正试图从本地服务器下载文件。如果找不到该文件,则下载该文件的方法将显示错误消息。是否可以从返回JsonResult的方法下载文件?
这是我认为的代码:
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);
}
奇怪的是,我测试了这是第一次,它的工作。我不记得改变任何东西,但现在该方法正常执行,但文件没有下载。请有人帮助我吗?
您确定传入的ID是正确的?文件被找到并且文件存在? – gideon 2012-02-15 03:40:43
是的。我正在用调试器检查所有这些。我的猜测是,阿贾克斯阻止我的文件被下载 – 2012-02-15 04:09:29
这不是你应该使用的解决方案,但是如果你陷入困境并且没有其他的解决方案,你可以试试这个:将文件下载方法移动到控制器/操作上(非ajaxed)。如果找到该文件,请将重定向发送到文件下载操作。不知道这是否会奏效,但我很确定这不是理想的答案。 – rkw 2012-02-15 06:25:42