在我的 Angular JS 项目中,我有一个 <a>
anchor 标记,单击时生成 HTTP GET
请求返回文件的 WebAPI 方法。
现在,我希望在请求成功后将文件下载给用户。我该怎么做?
anchor 标签:
<a href="#" ng-click="getthefile()">Download img</a>
AngularJS:
$scope.getthefile = function () {
$http({
method: 'GET',
cache: false,
url: $scope.appPath + 'CourseRegConfirm/getfile',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(function (data, status) {
console.log(data); // Displays text data if the file is a text file, binary if it's an image
// What should I write here to download the file I receive from the WebAPI method?
}).error(function (data, status) {
// ...
});
}
我的 WebAPI 方法:
[Authorize]
[Route("getfile")]
public HttpResponseMessage GetTestFile()
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.jpg");
if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
// Serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "SampleImg";
}
return result;
}
最佳答案
使用ajax下载二进制文件的支持不是很好,还是很多under development as working drafts .
简单下载方法:
您只需使用下面的代码就可以让浏览器下载请求的文件,这在所有浏览器中都支持,并且显然会同样触发 WebApi 请求。
$scope.downloadFile = function(downloadPath) {
window.open(downloadPath, '_blank', '');
}
ajax二进制下载方法:
使用 ajax 下载二进制文件可以在某些浏览器中完成,下面是一个适用于最新版本的 Chrome、Internet Explorer、FireFox 和 Safari 的实现。
它使用 arraybuffer
响应类型,然后将其转换为 JavaScript blob
,然后使用 saveBlob
将其呈现以保存方法 - 尽管这目前仅存在于 Internet Explorer 中 - 或变成由浏览器打开的 blob 数据 URL,如果支持在浏览器中查看 mime 类型,则触发下载对话框。
Internet Explorer 11 支持(已修复)
注意:Internet Explorer 11 不喜欢使用 msSaveBlob
函数(如果它已被别名)- 可能是安全功能,但更有可能是缺陷,因此使用 var saveBlob =导航器.msSaveBlob || navigator.webkitSaveBlob ...等
确定可用的saveBlob
支持导致了异常;因此,为什么下面的代码现在单独测试 navigator.msSaveBlob
。谢谢?微软
// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
// Use an arraybuffer
$http.get(httpPath, { responseType: 'arraybuffer' })
.success( function(data, status, headers) {
var octetStreamMime = 'application/octet-stream';
var success = false;
// Get the headers
headers = headers();
// Get the filename from the x-filename header or default to "download.bin"
var filename = headers['x-filename'] || 'download.bin';
// Determine the content type from the header or default to "application/octet-stream"
var contentType = headers['content-type'] || octetStreamMime;
try
{
// Try using msSaveBlob if supported
console.log("Trying saveBlob method ...");
var blob = new Blob([data], { type: contentType });
if(navigator.msSaveBlob)
navigator.msSaveBlob(blob, filename);
else {
// Try using other saveBlob implementations, if available
var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
if(saveBlob === undefined) throw "Not supported";
saveBlob(blob, filename);
}
console.log("saveBlob succeeded");
success = true;
} catch(ex)
{
console.log("saveBlob method failed with the following exception:");
console.log(ex);
}
if(!success)
{
// Get the blob url creator
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if(urlCreator)
{
// Try to use a download link
var link = document.createElement('a');
if('download' in link)
{
// Try to simulate a click
try
{
// Prepare a blob URL
console.log("Trying download link method with simulated click ...");
var blob = new Blob([data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
link.setAttribute('href', url);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
console.log("Download link method with simulated click succeeded");
success = true;
} catch(ex) {
console.log("Download link method with simulated click failed with the following exception:");
console.log(ex);
}
}
if(!success)
{
// Fallback to window.location method
try
{
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
console.log("Trying download link method with window.location ...");
var blob = new Blob([data], { type: octetStreamMime });
var url = urlCreator.createObjectURL(blob);
window.location = url;
console.log("Download link method with window.location succeeded");
success = true;
} catch(ex) {
console.log("Download link method with window.location failed with the following exception:");
console.log(ex);
}
}
}
}
if(!success)
{
// Fallback to window.open method
console.log("No methods worked for saving the arraybuffer, using last resort window.open");
window.open(httpPath, '_blank', '');
}
})
.error(function(data, status) {
console.log("Request failed with status: " + status);
// Optionally write the error out to scope
$scope.errorDetails = "Request failed with status: " + status;
});
};
用法:
var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);
注意事项:
您应该修改您的 WebApi 方法以返回以下 header :
我使用了
x-filename
header 来发送文件名。这是一个为方便起见的自定义 header ,但是您可以使用正则表达式从content-disposition
header 中提取文件名。您还应该为响应设置
content-type
mime header ,以便浏览器知道数据格式。
希望对您有所帮助。
关于c# - 使用 AngularJS 从 ASP.NET Web API 方法下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24080018/