所以当我尝试从服务器响应保存文件时遇到问题。
当我尝试从浏览器中的 url 下载文件时,一切正常,但当我尝试从 clint 端发送请求时,文件已保存,但文件中存在“[Object object]”,如果是 PDF 文件,则无法打开。
请求必须包含一个附加标头,其中包含客户端的密钥 ID。
这是我的服务器代码:
[HttpGet, IsAllowed(4,PageAction.Download)]
public HttpResponseMessage Download(string id)
{
var path = HttpContext.Current.Server.MapPath("~") + string.Format(@"Files\{0}.doc",id);
var stream = new FileStream(path, FileMode.Open);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = string.Format("{0}.doc", id);
return result;
}
这是我的客户端代码:
function get() {
var defer = $q.defer();
$http.post('http://localhost:4704/api/file/download/1', { responseType: 'arrayBuffer' }).then(
function (data, status, headers, config) {
var results = {
data: data,
headers: data.headers(),
status: data.status,
config: data.config
};
defer.resolve(results);
}, function (data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
}
$scope.download = function () {
get().then(function (response) {
var octetStreamMime = 'application/octet-stream';
var fileName = "Test.doc";
var contentType = response.headers["content-type"] || octetStreamMime;
try {
var blob = new Blob([response.data], { type: contentType });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
} catch (exc) {
console.log("Save Blob method failed with the following exception.");
console.log(exc);
}
}, function (error) {
});
另外,我还尝试了以下代码:
$http.get("http://localhost:4704/api/file/download").then(function (res) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/doc;charset=utf-8,',
target: '_blank',
download: 'test.doc'
})[0].click();
})