【发布时间】:2017-07-19 22:44:25
【问题描述】:
我一直在尝试关注有关下载从我的 Web API 发送的文件的不同帖子。到目前为止,我可以获取文件,它将打开下载窗口并保存。但是,我无法打开它,所以某处一定有问题。
到目前为止,这是我的 AngularJS。
return $http({
url: State.Endpoint + "/api/account/picture",
method: "GET",
responseType: 'arrayBuffer'
}).then(function (data) {
var octetStreamMime = 'application/octet-stream';
var success = false;
var file = new Blob([data.data], {
type: "image/jpeg"
});
var fileUrl = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileUrl;
a.target = "_blank";
a.download = "myFile.jpg";
document.body.appendChild(a);
a.click();
});
这将使我为我成功下载图像。但是,这不允许我打开文件,因此客户端或服务器端仍然有问题。
服务器端代码:
[Route("picture")]
[HttpGet]
public HttpResponseMessage GetPictureBlob()
{
HttpResponseMessage response = null;
var localFilePath = HttpContext.Current.Server.MapPath("~/Content/Images/demo.jpg");
if (!File.Exists(localFilePath))
{
response = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
var fStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);
// Serve the file to the client
response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(fStream)
};
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(fStream.Name)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
//response.Headers.Add("content-type", "application/octet-stream");
}
return response;
}
【问题讨论】:
-
this doesn't let me open the file是什么意思? -
当我使用画图、Photoshop 等任何工具打开文件时,它都不会显示图像。
-
你提到下载文件,你的意思是显示图像,因为这就是你的代码正在做的事情......如果你想将图像下载到浏览器,那么我会使用插件对于称为 FileSaver 的文件,您可以简单地将该文件保存在客户端。干杯!
-
是的,我的目标是为客户提供他们要保存到本地计算机的文件。
标签: angularjs download asp.net-web-api2 angularjs-http