[英]download file from 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;
在我的客户端之后,我尝试这样做:
.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();
}
这就是我的回答
我得到了什么:
有什么帮助吗?
只需将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;
在此链接中查看ContentDisposition
标头中的更多信息
更改方法的返回类型。 你可以写这样的方法。
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")
当您打开流时,您希望将其内容作为文件返回
[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 core 中
[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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.