我想下載從Web API返回到角客戶端的文件。問題在於文件未打開,即PDF瀏覽器顯示「未能加載」或文本文件在「未定義」內容中。爲清晰起見,請查看屏幕截圖。無法通過webapi在瀏覽器angularjs中顯示文件
我從服務器返回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);
}
UI:
$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」)? –
我該如何傳遞無記名標記?使用初始令牌授權 – Haris
通過GET參數。 –