我很确定这是不可能的,但我想我会问...
我有一个FileResult
返回文件,当它工作时没有问题。当由于FileResult
某种原因出现错误时,我想在用户屏幕上显示异常错误消息,最好是在弹出窗口中。
我可以做一个 Ajax 帖子,它在成功时返回一个文件,如果不是则显示一条消息?
我很确定这是不可能的,但我想我会问...
我有一个FileResult
返回文件,当它工作时没有问题。当由于FileResult
某种原因出现错误时,我想在用户屏幕上显示异常错误消息,最好是在弹出窗口中。
我可以做一个 Ajax 帖子,它在成功时返回一个文件,如果不是则显示一条消息?
I think it is not possible cause in order to handle ajax post, you will have to write a javascript handler on the client side and javascript cannot do file IO on client side.
However, what you can do is, make an ajax request to check if file exists and can be downloaded. If, not, respond to that request negatively which will popup a dialog on client side. If successful, make a file download request.
与MVC没有特别关系,但是......
它可以与允许您处理二进制数据(在您的情况下从 http 响应中获取)并将其保存到本地文件系统XMLHttpRequest
的新 HTML5 结合使用来完成。File System API
请参阅此处的示例:http: //www.html5rocks.com/en/tutorials/file/xhr2/#toc-example-savingimages
控制器(MyApiController)代码:
public ActionResult DownloadFile(String FileUniqueName)
{
var rootPath = Server.MapPath("~/UploadedFiles");
var fileFullPath = System.IO.Path.Combine(rootPath,FileUniqueName);
byte[] fileBytes = System.IO.File.ReadAllBytes(fileFullPath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "MyDownloadFile");
}
jQuery代码:
$(document).on("click"," a ", function(){ //on click of anchor tag
var funame=$(this).attr('uname'); /*anchor tag attribute "uname" contain file unique name*/
var url = "http://localhost:14211/MyApi/DownloadFile?FileUniqueName= " + funame;
window.open(url);
});