在MVC中下载docx文件

时间:2014-07-11 12:08:24

标签: asp.net-mvc-4

我上传了docx文件,然后我想下载docx文件,当我去下载然后出现一些问题,问题如下图所示

enter image description here

enter image description here

我的代码看起来像这样

        [HttpGet]
        public HttpResponseBase DownloadMapCyclo(Int32 CourseInfoCycloID = -1)
        {
            try
            {
                Response.AddHeader("Content-Disposition", "Attachment;filename=file.docx");
                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.OutputStream.Write(byteArrays, 0, byteArrays.Length);
                return Response;
            }
            catch (Exception ex)
            {
                Response.Output.WriteLine("<h1>" + ex.Message + "</h1><br/><hr/>" + ex.InnerException.InnerException.Message);
                return Response;
            }
        }

你有这个下载的任何解决方案..谢谢

2 个答案:

答案 0 :(得分:1)

不是写入Response对象(从而将代码与活动的HTTP上下文耦合),而只需返回ActionResult形式的方法并使用the File() helper method来响应文件

public ActionResult DownloadMapCyclo(Int32 CourseInfoCycloID = -1)
{
    //...
    return File(byteArrays, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "file.docx");
}

答案 1 :(得分:0)

您的退货类型为response,请将其更改为file类型

File(byteArrays, "application/docx", "PropsedChanges.docx");