2016-08-06 70 views
1

我是mvc4的新手。我用下面的代碼從服務器下載文件到客戶端控制器:文件下載不工作在asp.net mvc 4

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; 
} 

哪裏下載功能是:

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); 
} 

到控制器的呼叫是來自阿賈克斯:

$.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"); 
     } 
    } 
}); 

但下載不起作用,甚至沒有返回任何錯誤。請幫助

回答

0
$.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"); 
     } 
    } 
}); 

在成功阻止你的Ajax請求,你必須編寫代碼:

$.ajax({ 
    type: "POST", 
    url:'/Home/Download', 
    data: { option_id: 2 }, 
    //dataType: 'json', encode: true, 
    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"); 
     } 
    } 
}); 

你必須全局設置值的選項ID和成功部分聲明它...

enter image description here

+0

請嘗試正確格式化您的代碼... – andreas