2017-08-11 127 views
0

我想从asp.net web api下载文件(.docx)。从asp.net web api下载文件

因为我已经有服务器中的文件我将路径设置为现有的一个,然后我按照一些sugested计算器上做此:

docDestination是我的道路。

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); 
    var stream = new FileStream(docDestination, FileMode.Open, FileAccess.Read); 
    result.Content = new StreamContent(stream); 
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); 
    return result; 

后,关于我的客户端我试着这样做:

.then(response => { 
      console.log("here lives the response:", response); 
      var headers = response.headers; 
      var blob = new Blob([response.body], { type: headers['application/vnd.openxmlformats-officedocument.wordprocessingml.document'] }); 
      var link = document.createElement('a'); 
      link.href = window.URL.createObjectURL(blob); 
      link.download = "Filename"; 
      link.click(); 
     } 

这是我得到我的回应

response

我得到:

what i get

有帮助吗?

回答

2

更改方法的返回类型。你可以写这样的方法。

public FileResult TestDownload() 
{ 
    FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("YOUR PATH TO DOC"), "application/msword") 
    { 
     FileDownloadName = "myFile.docx" 
    }; 

    return result; 
} 

在客户端,你只需要有一个链接按钮。一旦你点击按钮,文件将被下载。只需在cshtml文件中写入此行。用您的控制器名称替换控制器名称。

@Html.ActionLink("Button 1", "TestDownload", "YourCOntroller") 
+0

我怎样才能得到它在客户端? –

+0

@FilipeCosta,更新了我的答案。请看一看。 –

+0

我不使用剃刀语法 –

-1

当你有流开,你想回到它是作为一个文件

[HttpGet] 
public async Task<FileStreamResult> Stream() 
{ 
    var stream = new MemoryStream(System.IO.File.ReadAllBytes("physical path of file")); 
    var response = File(stream, "Mime Type of file"); 
    return response; 
} 

您可以使用它,当你有一个字节数组,你想退回的文件内容

[HttpGet] 
public async Task<FileContentResult> Content() 
{ 
    var result = new FileContentResult(System.IO.File.ReadAllBytes("physical path of file"), "Mime Type of file") 
    { 
     FileDownloadName = "Your FileName" 
    }; 
    return result; 
} 

当你在磁盘上有一个文件并且想要返回它的内容(你给出一个路径)-------------只在asp.net核心中

[HttpGet] 
public async Task<IActionResult> PhysicalPath() 
{ 
    var result = new PhysicalFileResult("physical path of file", "Mime Type of file") 
    { 
     FileDownloadName = "Your FileName", 
     FileName = "physical path of file" 
    }; 
    return result; 
} 
+0

你为什么试着抓住一切?没有必要为了证明你的答案。 – mason

+0

为什么你将字符串值传递给你的'HttpGet'属性?这不会编译。 – mason

+0

[属性路由asp.net核心](“https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing#attribute-routing”) – Khalil