【发布时间】:2017-08-07 15:49:40
【问题描述】:
我正在尝试将从 Web API 返回的文件下载到 Angular 客户端。问题是文件没有打开,即浏览器在内容“未定义”中显示“加载失败”或文本文件的 pdf。为了清楚起见,请查看屏幕截图。
我正在从服务器返回一个HttpResponseMessage,response.Content 包含从 wcf 服务返回的文件的MemoryStream。
我不确定为什么它不起作用,我已经尝试了这里建议的一些东西,并查看了其他一些文章。
我已将 responseType 设置为 arraybuffer,尝试返回 ByteArrayConent、StreamContent。
在 UI 中,尝试创建 blob 和文件,进一步调用 window.URL.createObjectURL 和 window.open 方法以及尝试 window.location.href。
为了排除流是否有问题,在 asp.net mvc 应用程序中测试了返回的流,它返回并在浏览器中按预期打开文件。所以从 wcf 服务返回的流是好的。
服务器:
public HttpResponseMessage DownloadDocument(string filename)
{
var proxy = new WCFService();
Stream fileStream = null;
var storage = proxy.GetObject("param", "foo.txt", "param", out fileStream);
if (fileStream != null)
{
var mstream = new MemoryStream();
fileStream.CopyTo(mstream);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
//Content = new StreamContent(mstream)
Content = new ByteArrayContent(mstream.ToArray())
};
result.Content.Headers.ContentLength = mstream.Length;
result.Content.Headers.ContentType = new MediaTypeHeaderValue(storage.ContentType);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachement")
{
FileName = storage.FileName,
Size = mstream.Length
};
return result;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
用户界面:
$http.get('http://service/api/doc/downloaddoc?filename=null', { responseType: 'arraybuffer' })
.success(function (data) {
var contentType = 'application/pdf';
var blob = new Blob([data], { type: contentType });
var file = new File([blob], 'foo.pdf');
var url = window.URL.createObjectURL(blob);
window.open(url, 'f');
}
也试过了:
var reader = new FileReader();
var out = new Blob([this.response], { type: contentType });
reader.onload = function (e) {
window.open(reader.result);
}
reader.readAsDataURL(out);
【问题讨论】:
-
为什么不简单做
window.open("http://service/api/doc/downloaddoc?filename=null")? -
我如何以这种方式传递不记名令牌?使用 ouath 令牌授权
-
通过 GET 参数。
-
在 GET 参数中其实不直接传递 oauth token。生成另一个 OPT 并在 GET 参数中传递该令牌。 stackoverflow.com/a/28287491/2509344
-
这对我来说似乎不是满足我需要的好方法
标签: javascript c# angularjs asp.net-web-api