为什么从Controller返回的.docx文件已损坏?

问题描述

我有一个.NET Core 2.2 Web应用程序。我有一个Controller方法,该方法对Word文档进行一些编辑,然后将其返回给客户端。但是,当我尝试查看返回的文档时,出现以下对话框:

corrupt file dialog

我尝试了多种方法。这是控制器方法的一部分(请注意先前尝试中注释掉的内容!)

byte[] byteArray = System.IO.File.ReadAllBytes(compositeFileName);
//MemoryStream content;

//content = new MemoryStream(byteArray);
//string contentType = "application/octet-stream";
//return File(content,contentType,compositeFileName);
//return File(byteArray,"application/vnd.openxmlformats-officedocument.wordprocessingml.document",compositeFileName);
return new FileContentResult(byteArray,"application/vnd.openxmlformats-officedocument.wordprocessingml.document");

这是javascript(来自vue.js文件

self.$http
    .post('/MyController/MyMethod',myData,self.IENoCacheHeaders)
    .then(function (response) {
         var blob = new Blob([response.body],{type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })
         var link = document.createElement('a')
         link.href = window.URL.createObjectURL(blob)
         link.download = 'test.docx'
         link.click()

我已经查看了response.body的内容,并且那里有一堆二进制数据。我尝试过交换MIME类型(主要是使用application / vnd.openxmlformats-officedocument.wordprocessingml.document和application / octet-stream,但无济于事。

有人对我在做什么错有任何见解吗?正在流回浏览器的文件(compositeFileName是服务器上.docx文件的路径)在服务器上正常-在流式传输并在客户端中对其进行处理的过程中出了点问题。

谢谢

爱德华

解决方法

我只需要简化我的方法:

self.$http
.post('/MyController/MyMethod',myData,{ responseType: 'blob' })
.then(function (response) {
     var link = document.createElement('a')
     link.href = window.URL.createObjectURL(response.body)
     link.download = 'test.docx'
     link.click()