2016-07-06 93 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(); 
    }