在asp.net mvc 4中文件下载不起作用
在asp.net mvc 4中文件下载不起作用
我是MVC4的新手。我在控制器中使用以下代码从服务器下载文件到客户端:\n
public ActionResult IndexSpecification(int option_id) { int cat = (int)Session["category_Name"]; int prod = (int)Session["product_ID"]; int user = (int)Session["logged_in"]; string twoinone = cat + "_" + prod; f1 = Download(twoinone); return f1; }
\n其中Download函数如下:\n
public FileResult Download(string twoinone) { var webClient = new WebClient(); byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(Server.MapPath("~/Download"), "a.rar")); string fileName = "Tellersoft.rar"; return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); }
\n调用控制器使用了ajax:\n
$.ajax({ type: "POST", url: base_url + '/Options/IndexSpecification', data: { option_id : 2 }, //dataType: 'json', encode: true, async: false, cache: false, success: function (data, status, jqXHR) { console.log(data); }, error: function (jqXHR, textStatus, errorThrown) { if (typeof (console) != 'undefined') { alert("oooppss"); } else { alert("something went wrong"); } } });
\n但是下载不起作用,也没有返回任何错误。请帮忙解决。
问题:在asp.net mvc 4中无法下载文件。原因:在ajax请求的成功块中没有正确的代码。解决方法:在ajax请求的成功块中添加以下代码:
$.ajax({ type: "POST", url:'/Home/Download', data: { option_id: 2 }, async: false, cache: false, success: function (data, status, jqXHR) { window.location = '/Home/Download?option_id=2'; }, error: function (jqXHR, textStatus, errorThrown) { if (typeof (console) != 'undefined') { alert("oooppss"); } else { alert("something went wrong"); } } });
并设置option id值为全局变量,在成功部分声明。