为什么下载文件会引发多个处置错误?

时间:2017-10-20 07:16:24

标签: c# asp.net-mvc asp.net-mvc-5

我使用的是webgrid,我在其中放了一个下载按钮,从网格中下载文件。

但它抛出一个错误: localhost发送了无效的响应。 ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION

 [HttpGet]
       public ActionResult DownloadStories()
       {

           string filename = "saddam.png";
           string filepath = Server.MapPath("~/UploadedFiles/") + filename; //AppDomain.CurrentDomain.BaseDirectory + "/UploadedFiles/" + filename;
           byte[] filedata = System.IO.File.ReadAllBytes(filepath);
           string contentType = MimeMapping.GetMimeMapping(filepath);

           var cd = new System.Net.Mime.ContentDisposition
           {
               FileName = filename,
               Inline = true,
           };

          // Response.AppendHeader("Content-Disposition", cd.ToString());
           Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

           return File(filedata, contentType, cd.FileName);


       }

查看:

 WebGrid wgImages = new WebGrid(listData, rowsPerPage: 20);
        @wgImages.GetHtml(tableStyle: "table table-condensed table-bordered table-striped table-responsive", 
        columns: wgImages.Columns(
                                  wgImages.Column
                                  (columnName: "Image", header:"Image"),
                                  wgImages.Column
                                  (columnName:"Story", header: "Story"),
                                  wgImages.Column
                                  (columnName:"Image", header:"Download", format: (testItem)=> Html.ActionLink("Download", "DownloadStories", "Stories")

                                 ))
        );
    }

我已经尝试了我现在评论过的代码,但这也无效。

1 个答案:

答案 0 :(得分:0)

为什么不使用简单的HTML& JAVASCRIPT通过进行ajax调用来下载文件

<强> 1。通过ajax post

调用此函数
[HttpPost]
       public JsonResult DownloadStories(String someParamsIfany)
       {
               //do your thing 

        return Json(file,JsonRequestBehavior.AllowGet);  
       }

<强> 2。用数据创建一个Img文件&amp;在Html Side下载

 $.ajax({  
            type: "POST",          
            url: '/Home/DownloadStories',   
            data: {someParamsIfany :someParamsIfany},  
            success: function (result) {  
                DownLoadTheFile(result);
            }
      });

3现在功能DownLoadTheFile

function DownLoadTheFile(file){
     var a = document.createElement('a');
    a.href = file.filepath ;
    a.download =  file.filename;
    a.click();
}