【问题标题】:Download a file with mvc使用 mvc 下载文件
【发布时间】:2016-11-02 21:07:05
【问题描述】:

我需要允许我网站上的用户下载一个文件(xml 文件)

我试过了

 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 () {

        });
}

但没有下载任何东西

【问题讨论】:

标签: javascript ajax asp.net-mvc-3


【解决方案1】:

是否必须使用 ajax 来完成?也许您可以打开另一个带有文件生成地址的窗口,让浏览器完成这项工作:

function downloadFile(id) {

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

}

【讨论】:

  • 为什么需要 id
【解决方案2】:

您不能使用 ajax post 下载文件。 它不能将文件直接保存到用户的机器中。 ajax 帖子将以原始格式获得响应,但它不会是文件。

随便用

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

【讨论】:

    【解决方案3】:

    很简单

    制作链接

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

    【讨论】:

      【解决方案4】:

      这是我完成下载的一种方式,希望对你有所帮助。

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

      【讨论】:

        猜你喜欢
        • 2016-05-16
        • 1970-01-01
        • 1970-01-01
        • 2015-05-29
        • 2017-03-06
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 2013-08-28
        相关资源
        最近更新 更多