Fil*_*sta 3 c# asp.net file download asp.net-web-api
我正在尝试从asp.net Web API下载文件(.docx)。
因为我已经在服务器中有一个文档,所以我将路径设置为现有文档的路径,然后按照stackoverflow上的提示进行操作:
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;
Run Code Online (Sandbox Code Playgroud)
之后,在我的客户端,我尝试执行以下操作:
.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();
}
Run Code Online (Sandbox Code Playgroud)
这就是我的回应
我得到什么:
有什么帮助吗?
更改方法的返回类型。你可以写这样的方法。
public FileResult TestDownload()
{
FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("YOUR PATH TO DOC"), "application/msword")
{
FileDownloadName = "myFile.docx"
};
return result;
}
Run Code Online (Sandbox Code Playgroud)
在客户端,您只需要一个链接按钮。单击该按钮后,将下载文件。只需在 cshtml 文件中写入这一行。用您的控制器名称替换控制器名称。
@Html.ActionLink("Button 1", "TestDownload", "YourCOntroller")
Run Code Online (Sandbox Code Playgroud)
小智 5
只需将ContentDisposition其值添加到您的响应标头中attachment,浏览器就会将其解释为需要下载的文件
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(docDestination, FileMode.Open,FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "document.docx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
return result;
Run Code Online (Sandbox Code Playgroud)
在此链接中查找有关ComponentDisposition标头的更多信息
| 归档时间: |
|
| 查看次数: |
10031 次 |
| 最近记录: |