2016-07-06 83 views
0

我需要讓我的網站上用戶下載一個文件(XML文件)下載使用MVC文件

我試圖

public FileResult DownloadFile(string fileid) 
{ 
    if (!string.IsNullOrEmpty(fileid)) 
    {    
     byte[] fileBytes = Encoding.ASCII.GetBytes(FileData); 
     return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet,FileName + ".bccx"); 
    } 
     return null; 
} 

AJAX:

function downloadFile(id) { 
     $.ajax({ 
      url: sitePath + "Controller/DownloadFile?fileid=" + id, 
      type: 'post', 
      asysnc: false 
     }) 
     .done(function() { 

     }); 
} 

但沒有什麼是下載

+2

可能重複的[下載由jQuery.Ajax文件](http://stackoverflow.com/questio NS/4545311 /下載一個文件按jQuery的AJAX) – malarzm

回答

0

是否需要使用ajax來完成?也許你可以打開一個文件生成地址另一個窗口,讓瀏覽器做的工作:

function downloadFile(id) { 

    window.open(sitePath + "Controller/DownloadFile?fileid=" + id, '_blank'); 

} 
0

這是我完成下載的一種方式,希望有所幫助。

$.ajax({ 
      url: sitePath + "Controller/DownloadFile?fileid=" + id, 
      type: 'GET', 
      success: function (filename) { //I return the filename in from the controller 
       frame = document.createElement("iframe"); 
       frame.id = "iframe"; 
       frame.style.display = 'none'; 
       frame.src = '/FileDirectory?fileName=' + filename; //the path to the file 
       document.body.appendChild(frame); 
      }, 
      cache: false, 
      contentType: false, 
      processData: false 
     }); 
0

不能使用AJAX後下載文件。 它不能將文件直接保存到用戶的機器中。 ajax文章會以原始格式得到響應,但它不會是文件。

只需使用

function downloadFile(id) { 
    window.location = "/Controller/DownloadFile?fileid=" + id; 
} 
0

它是非常簡單

製作鏈接

<a href="/Home/preview?id=Chrysanthemum.jpg" > Download File</a> 

和控制器

public ActionResult preview(string id) 
     { 

      string Filename = Path.GetFileName(@id); 
      string location = id; 
      try 
     { 
      if (System.IO.File.Exists(location)) 
      { 

       FileStream F = new FileStream(@location, FileMode.Open, FileAccess.Read, FileShare.Read); 
       return File(F, "application/octet-stream", Filename); 
      } 

     } 
     catch (IOException ex) 
     { 


     } 
     return View(); 
    }