2017-08-11 56 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