我正試圖從本地服務器下載文件。如果找不到該文件,則下載該文件的方法將顯示錯誤消息。是否可以從返回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