如何下载具有 Angular2 或更高版本的文件
How do I download a file with Angular2 or greater
我有一个WebApi/MVC应用程序,我正在为其开发一个angular2客户端(以取代MVC(。我在理解 Angular 如何保存文件时遇到了一些麻烦。
请求还可以(在 MVC 上工作正常,我们可以记录收到的数据(,但我无法弄清楚如何保存下载的数据(我主要遵循与本文相同的逻辑(。我确信这非常简单,但到目前为止,我根本没有掌握它。
组件函数的代码如下。我已经尝试了不同的替代方案,据我所知,blob 方式应该是要走的路,但URL
中没有createObjectURL
的功能。我什至无法在窗口中找到URL
的定义,但显然它存在。如果我使用 FileSaver.js
模块,我会收到相同的错误。所以我想这是最近发生了变化或尚未实施的东西。如何触发以A2格式保存的文件?
downloadfile(type: string){
let thefile = {};
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(data => thefile = new Blob([data], { type: "application/octet-stream" }), //console.log(data),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
let url = window.URL.createObjectURL(thefile);
window.open(url);
}
为了完整起见,获取数据的服务如下所示,但它唯一要做的就是发出请求并在成功时传递数据而不进行映射:
downloadfile(runname: string, type: string){
return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
.catch(this.logAndPassOn);
}
问题是可观察量在另一个上下文中运行,因此当您尝试创建 URL var 时,您有一个空对象,而不是您想要的 blob。
解决此问题的众多方法之一如下:
this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
error => console.log('Error downloading the file.'),
() => console.info('OK');
当请求准备就绪时,它将调用函数"downloadFile",其定义如下:
downloadFile(data: Response) {
const blob = new Blob([data], { type: 'text/csv' });
const url= window.URL.createObjectURL(blob);
window.open(url);
}
blob 已完美创建,因此 URL var,如果未打开新窗口,请检查您是否已经导入了"rxjs/Rx";
import 'rxjs/Rx' ;
我希望这能帮助你。
试试这个!
1 - 安装显示保存/打开文件弹出窗口的依赖项
npm install file-saver --save
npm install -D @types/file-saver
2-使用此函数创建服务以接收数据
downloadFile(id): Observable<Blob> {
let options = new RequestOptions({responseType: ResponseContentType.Blob });
return this.http.get(this._baseUrl + '/' + id, options)
.map(res => res.blob())
.catch(this.handleError)
}
3-在组件中,使用"文件保护程序"解析blob
import {saveAs as importedSaveAs} from "file-saver";
this.myService.downloadFile(this.id).subscribe(blob => {
importedSaveAs(blob, this.fileName);
}
)
这对我有用!
如果你不需要在请求中添加标头,要在 Angular2 中下载文件,你可以做一个简单的(KISS 原则(:
window.location.href='http://example.com/myuri/report?param=x';
在您的组件中。
这是为那些正在寻找如何使用HttpClient和文件保护程序来做到这一点的人准备的:
- 安装文件保护程序
npm 安装文件保护程序 --保存
npm install @types/file-saver --save
API 服务类:
export() {
return this.http.get(this.download_endpoint,
{responseType: 'blob'});
}
元件:
import { saveAs } from 'file-saver';
exportPdf() {
this.api_service.export().subscribe(data => saveAs(data, `pdf report.pdf`));
}
这个怎么样?
this.http.get(targetUrl,{responseType:ResponseContentType.Blob})
.catch((err)=>{return [do yourself]})
.subscribe((res:Response)=>{
var a = document.createElement("a");
a.href = URL.createObjectURL(res.blob());
a.download = fileName;
// start download
a.click();
})
我可以用它。
无需额外的包装。
对于较新的角度版本:
npm install file-saver --save
npm install @types/file-saver --save
import {saveAs} from 'file-saver';
this.http.get('endpoint/', {responseType: "blob", headers: {'Accept': 'application/pdf'}})
.subscribe(blob => {
saveAs(blob, 'download.pdf');
});
正如Alejandro Corredor所提到的,这是一个简单的范围错误。subscribe
是异步运行的,open
必须放置在该上下文中,以便在我们触发下载时完成数据加载。
也就是说,有两种方法可以做到这一点。正如文档建议的那样,该服务负责获取和映射数据:
//On the service:
downloadfile(runname: string, type: string){
var headers = new Headers();
headers.append('responseType', 'arraybuffer');
return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
.map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
.catch(this.logAndPassOn);
}
然后,在组件上,我们只需订阅并处理映射的数据。有两种可能性。第一个,如原始帖子中所建议的,但需要像亚历杭德罗指出的那样进行小的更正:
//On the component
downloadfile(type: string){
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(data => window.open(window.URL.createObjectURL(data)),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
}
第二种方法是使用FileReader。逻辑是相同的,但我们可以显式等待 FileReader 加载数据,避免嵌套,并解决异步问题。
//On the component using FileReader
downloadfile(type: string){
var reader = new FileReader();
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(res => reader.readAsDataURL(res),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
reader.onloadend = function (e) {
window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no');
}
}
注意:我正在尝试下载Excel文件,即使下载被触发(所以这回答了问题(,该文件已损坏。请参阅这篇文章的答案,以避免损坏的文件。
下载 .zip angular 2.4.x 的解决方案:您必须从 '@angular/http' 导入 ResponseContentType,并将 responseType 更改为 ResponseContentType.ArrayBuffer(默认情况下为 ResponseContentType.Json(
getZip(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
let headers = this.setHeaders({
'Content-Type': 'application/zip',
'Accept': 'application/zip'
});
return this.http.get(`${environment.apiUrl}${path}`, {
headers: headers,
search: params,
responseType: ResponseContentType.ArrayBuffer //magic
})
.catch(this.formatErrors)
.map((res:Response) => res['_body']);
}
我将 Angular 4 与 4.3 httpClient 对象一起使用。我修改了我在 Js 的技术博客中找到的答案,该答案创建了一个链接对象,使用它进行下载,然后销毁它。
客户:
doDownload(id: number, contentType: string) {
return this.http
.get(this.downloadUrl + id.toString(), { headers: new HttpHeaders().append('Content-Type', contentType), responseType: 'blob', observe: 'body' })
}
downloadFile(id: number, contentType: string, filename:string) {
return this.doDownload(id, contentType).subscribe(
res => {
var url = window.URL.createObjectURL(res);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}
this.downloadUrl 的值之前已设置为指向 api。我正在使用它来下载附件,所以我知道 id、contentType 和文件名:我正在使用 MVC API 返回文件:
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public FileContentResult GetAttachment(Int32 attachmentID)
{
Attachment AT = filerep.GetAttachment(attachmentID);
if (AT != null)
{
return new FileContentResult(AT.FileBytes, AT.ContentType);
}
else
{
return null;
}
}
附件类如下所示:
public class Attachment
{
public Int32 AttachmentID { get; set; }
public string FileName { get; set; }
public byte[] FileBytes { get; set; }
public string ContentType { get; set; }
}
filerep 存储库从数据库中返回文件。
希望这对某人有所帮助:)
通过ajax下载文件总是一个痛苦的过程,在我看来,最好让服务器和浏览器来完成内容类型协商的工作。
我认为最好有
<a href="api/sample/download"></a>
来做。这甚至不需要打开任何新窗口之类的东西。
示例中的 MVC 控制器可能如下所示:
[HttpGet("[action]")]
public async Task<FileContentResult> DownloadFile()
{
// ...
return File(dataStream.ToArray(), "text/plain", "myblob.txt");
}
如果你尝试在你subscribe
里面调用新方法会更好
this._reportService.getReport()
.subscribe((data: any) => {
this.downloadFile(data);
},
(error: any) => сonsole.log(error),
() => console.log('Complete')
);
在函数downloadFile(data)
内部,我们需要block, link, href and file name
downloadFile(data: any, type: number, name: string) {
const blob = new Blob([data], {type: 'text/csv'});
const dataURL = window.URL.createObjectURL(blob);
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
const link = document.createElement('a');
link.href = dataURL;
link.download = 'export file.csv';
link.click();
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(dataURL);
}, 100);
}
}
好吧,我写了一段受上述许多答案启发的代码,这些代码应该很容易在服务器发送带有内容处置标头的文件的大多数情况下工作,而无需任何第三方安装,除了 rxjs 和 Angular。
首先,如何从组件文件中调用代码
this.httpclient.get(
`${myBackend}`,
{
observe: 'response',
responseType: 'blob'
}
).pipe(first())
.subscribe(response => SaveFileResponse(response, 'Custom File Name.extension'));
如您所见,它基本上几乎是来自angular的平均后端调用,有两个变化。
- 我正在观察反应而不是身体
- 我明确表示响应是一个斑点
从服务器获取文件后,我原则上将保存文件的整个任务委托给帮助程序函数,我将其保存在单独的文件中,并导入到我需要的任何组件中
export const SaveFileResponse =
(response: HttpResponse<Blob>,
filename: string = null) =>
{
//null-checks, just because :P
if (response == null || response.body == null)
return;
let serverProvidesName: boolean = true;
if (filename != null)
serverProvidesName = false;
//assuming the header is something like
//content-disposition: attachment; filename=TestDownload.xlsx; filename*=UTF-8''TestDownload.xlsx
if (serverProvidesName)
try {
let f: string = response.headers.get('content-disposition').split(';')[1];
if (f.includes('filename='))
filename = f.substring(10);
}
catch { }
SaveFile(response.body, filename);
}
//Create an anchor element, attach file to it, and
//programmatically click it.
export const SaveFile = (blobfile: Blob, filename: string = null) => {
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blobfile);
a.download = filename;
a.click();
}
在那里,不再有神秘的 GUID 文件名!我们可以使用服务器提供的任何名称,而不必在客户端中显式指定它,或者覆盖服务器提供的文件名(如本例所示(。此外,如果需要,可以轻松地更改从内容处置中提取文件名的算法以满足他们的需求,其他所有内容都不会受到影响 - 如果在此类提取过程中出错,它只会传递"null"作为文件名。
正如另一个答案已经指出的那样,IE一如既往地需要一些特殊处理。但是随着Chromium Edge在几个月内到来,我在构建新应用程序时不会担心这一点(希望如此(。还有撤销 URL 的问题,但我对此有点不确定,所以如果有人可以在评论中提供帮助,那就太棒了。
对于那些使用 Redux 模式的人
我在文件保存程序中添加了@Hector奎瓦斯在他的回答中提到的。使用 Angular2 v. 2.3.1,我不需要添加@types/文件保护程序。
以下示例是将期刊下载为 PDF。
日记操作
public static DOWNLOAD_JOURNALS = '[Journals] Download as PDF';
public downloadJournals(referenceId: string): Action {
return {
type: JournalActions.DOWNLOAD_JOURNALS,
payload: { referenceId: referenceId }
};
}
public static DOWNLOAD_JOURNALS_SUCCESS = '[Journals] Download as PDF Success';
public downloadJournalsSuccess(blob: Blob): Action {
return {
type: JournalActions.DOWNLOAD_JOURNALS_SUCCESS,
payload: { blob: blob }
};
}
日记效应
@Effect() download$ = this.actions$
.ofType(JournalActions.DOWNLOAD_JOURNALS)
.switchMap(({payload}) =>
this._journalApiService.downloadJournal(payload.referenceId)
.map((blob) => this._actions.downloadJournalsSuccess(blob))
.catch((err) => handleError(err, this._actions.downloadJournalsFail(err)))
);
@Effect() downloadJournalSuccess$ = this.actions$
.ofType(JournalActions.DOWNLOAD_JOURNALS_SUCCESS)
.map(({payload}) => saveBlobAs(payload.blob, 'journal.pdf'))
日记帐服务
public downloadJournal(referenceId: string): Observable<any> {
const url = `${this._config.momentumApi}/api/journals/${referenceId}/download`;
return this._http.getBlob(url);
}
HTTP 服务
public getBlob = (url: string): Observable<any> => {
return this.request({
method: RequestMethod.Get,
url: url,
responseType: ResponseContentType.Blob
});
};
轴颈减速机虽然这只设置了我们应用程序中使用的正确状态,但我仍然想添加它以显示完整的模式。
case JournalActions.DOWNLOAD_JOURNALS: {
return Object.assign({}, state, <IJournalState>{ downloading: true, hasValidationErrors: false, errors: [] });
}
case JournalActions.DOWNLOAD_JOURNALS_SUCCESS: {
return Object.assign({}, state, <IJournalState>{ downloading: false, hasValidationErrors: false, errors: [] });
}
我希望这是有帮助的。
我分享了帮助我的解决方案(任何改进都非常感谢(
在您的服务">服务"上:
getMyFileFromBackend(typeName: string): Observable<any>{
let param = new URLSearchParams();
param.set('type', typeName);
// setting 'responseType: 2' tells angular that you are loading an arraybuffer
return this.http.get(http://MYSITE/API/FILEIMPORT, {search: params, responseType: 2})
.map(res => res.text())
.catch((error:any) => Observable.throw(error || 'Server error'));
}
组成部分 :
downloadfile(type: string){
this.pservice.getMyFileFromBackend(typename).subscribe(
res => this.extractData(res),
(error:any) => Observable.throw(error || 'Server error')
);
}
extractData(res: string){
// transforme response to blob
let myBlob: Blob = new Blob([res], {type: 'application/vnd.oasis.opendocument.spreadsheet'}); // replace the type by whatever type is your response
var fileURL = URL.createObjectURL(myBlob);
// Cross your fingers at this point and pray whatever you're used to pray
window.open(fileURL);
}
在组件部分,您可以在不订阅响应的情况下调用服务。订阅有关 openOffice MIME 类型的完整列表,请参阅: http://www.openoffice.org/framework/documentation/mimetypes/mimetypes.html <</p>
要下载和显示PDF文件,截取的非常相似的代码如下所示:
private downloadFile(data: Response): void {
let blob = new Blob([data.blob()], { type: "application/pdf" });
let url = window.URL.createObjectURL(blob);
window.open(url);
}
public showFile(fileEndpointPath: string): void {
let reqOpt: RequestOptions = this.getAcmOptions(); // getAcmOptions is our helper method. Change this line according to request headers you need.
reqOpt.responseType = ResponseContentType.Blob;
this.http
.get(fileEndpointPath, reqOpt)
.subscribe(
data => this.downloadFile(data),
error => alert("Error downloading file!"),
() => console.log("OK!")
);
}
这是我在我的情况下做的事情 -
// service method
downloadFiles(vendorName, fileName) {
return this.http.get(this.appconstants.filesDownloadUrl, { params: { vendorName: vendorName, fileName: fileName }, responseType: 'arraybuffer' }).map((res: ArrayBuffer) => { return res; })
.catch((error: any) => _throw('Server error: ' + error));
}
// a controller function which actually downloads the file
saveData(data, fileName) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
let blob = new Blob([data], { type: "octet/stream" }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
// a controller function to be called on requesting a download
downloadFiles() {
this.service.downloadFiles(this.vendorName, this.fileName).subscribe(data => this.saveData(data, this.fileName), error => console.log("Error downloading the file."),
() => console.info("OK"));
}
解决方案参考自 - 这里
我发现到目前为止的答案缺乏洞察力和警告。您可以并且应该注意与IE10+的不兼容(如果您关心的话(。
这是应用程序部分和服务部分之后的完整示例。请注意,我们设置了观察:"响应">来捕获文件名的标头。另请注意,Content-Disposition 标头必须由服务器设置和公开,否则当前的 Angular HttpClient 将不会传递它。我在下面添加了一个dotnet核心代码段。
public exportAsExcelFile(dataId: InputData) {
return this.http.get(this.apiUrl + `event/export/${event.id}`, {
responseType: "blob",
observe: "response"
}).pipe(
tap(response => {
this.downloadFile(response.body, this.parseFilename(response.headers.get('Content-Disposition')));
})
);
}
private downloadFile(data: Blob, filename: string) {
const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;'});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
private parseFilename(contentDisposition): string {
if (!contentDisposition) return null;
let matches = /filename="(.*?)"/g.exec(contentDisposition);
return matches && matches.length > 1 ? matches[1] : null;
}
Dotnet core,具有 Content-Disposition 和 MediaType
private object ConvertFileResponse(ExcelOutputDto excelOutput)
{
if (excelOutput != null)
{
ContentDisposition contentDisposition = new ContentDisposition
{
FileName = excelOutput.FileName.Contains(_excelExportService.XlsxExtension) ? excelOutput.FileName : "TeamsiteExport.xlsx",
Inline = false
};
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
return File(excelOutput.ExcelSheet, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
else
{
throw new UserFriendlyException("The excel output was empty due to no events.");
}
}
使用文件保存程序和 HttpClient 更新了 Hector 在第 2 步的答案:
public downloadFile(file: File): Observable<Blob> {
return this.http.get(file.fullPath, {responseType: 'blob'})
}
以下代码对我有用
使 HTML 像这样:
<button type="button" onclick="startDownload(someData)">Click to download!</button>
JS如下:
let someData = {};
someData.name = 'someName';
someData.fileurl= 'someUrl';
function startDownload(someData){
let link = document.createElement('a');
link.href = someData.fileurl; //data is object received as response
link.download = someData.fileurl.substr(someData.fileurl.lastIndexOf('/') + 1);
link.click();
}
我得到了从 angular 2 下载而不会损坏的解决方案,使用弹簧 MVC 和角度 2
1st-我的返回类型是:-来自java端的响应实体。在这里,我发送的 byte[] 数组具有来自控制器的返回类型。
2nd- 将文件保护程序包含在工作区中 - 在索引页中作为:
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
3rd- 在组件 TS 编写以下代码:
import {ResponseContentType} from '@angular.core';
let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' });
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.http
.post('/project/test/export',
somevalue,options)
.subscribe(data => {
var mediaType = 'application/vnd.ms-excel';
let blob: Blob = data.blob();
window['saveAs'](blob, 'sample.xls');
});
这将为您提供 xls 文件格式。如果需要其他格式,请使用正确的扩展名更改媒体类型和文件名。
<a href="my_url" download="myfilename">Download file</a>
my_url应具有相同的来源,否则它将重定向到该位置
我今天遇到了同样的情况,我不得不下载一个 pdf 文件作为附件(该文件不应该在浏览器中呈现,而是下载(。为了实现这一点,我发现我必须在 Angular Blob
中获取文件,同时在响应中添加一个 Content-Disposition
标头。
这是我能得到的最简单的(Angular 7(:
服务内部:
getFile(id: String): Observable<HttpResponse<Blob>> {
return this.http.get(`./file/${id}`, {responseType: 'blob', observe: 'response'});
}
然后,当我需要下载组件中的文件时,我可以简单地:
fileService.getFile('123').subscribe((file: HttpResponse<Blob>) => window.location.href = file.url);
更新:
从服务中删除了不必要的标头设置
Angular 12 + ASP.NET 5 WEB API
可以从服务器返回 Blob 对象并创建定位标记,并将 href 属性设置为从 Blob 创建的对象 URL。现在单击锚点将下载文件。您也可以设置文件名。
downloadFile(path: string): Observable<any> {
return this._httpClient.post(`${environment.ApiRoot}/accountVerification/downloadFile`, { path: path }, {
observe: 'response',
responseType: 'blob'
});
}
saveFile(path: string, fileName: string): void {
this._accountApprovalsService.downloadFile(path).pipe(
take(1)
).subscribe((resp) => {
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(resp.body);
downloadLink.setAttribute('download', fileName);
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
});
}
后端
[HttpPost]
[Authorize(Roles = "SystemAdmin, SystemUser")]
public async Task<IActionResult> DownloadFile(FilePath model)
{
if (ModelState.IsValid)
{
try
{
var fileName = System.IO.Path.GetFileName(model.Path);
var content = await System.IO.File.ReadAllBytesAsync(model.Path);
new FileExtensionContentTypeProvider()
.TryGetContentType(fileName, out string contentType);
return File(content, contentType, fileName);
}
catch
{
return BadRequest();
}
}
return BadRequest();
}
let headers = new Headers({
'Content-Type': 'application/json',
'MyApp-Application': 'AppName',
'Accept': 'application/vnd.ms-excel'
});
let options = new RequestOptions({
headers: headers,
responseType: ResponseContentType.Blob
});
this.http.post(this.urlName + '/services/exportNewUpc', localStorageValue, options)
.subscribe(data => {
if (navigator.appVersion.toString().indexOf('.NET') > 0)
window.navigator.msSaveBlob(data.blob(), "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+".xlsx");
else {
var a = document.createElement("a");
a.href = URL.createObjectURL(data.blob());
a.download = "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+ ".xlsx";
a.click();
}
this.ui_loader = false;
this.selectedexport = 0;
}, error => {
console.log(error.json());
this.ui_loader = false;
document.getElementById("exceptionerror").click();
});
只需将url
href
如下所示。
<a href="my_url">Download File</a>
直接从使用下载属性的模板下载文件,[attr.href]
可以从组件提供属性值。这个简单的解决方案应该适用于大多数浏览器。
<a download [attr.href]="yourDownloadLink"></a>
参考: https://www.w3schools.com/tags/att_a_download.asp
创建一个临时锚标记,然后使用 Javascript 以编程方式单击它
async function downloadFile(fileName) {
const url = document.getElementById("url").value
const link = document.createElement('a');
link.href = await toDataURL(url);
link.setAttribute('download', fileName ? fileName : url.split('/').pop());
link.setAttribute('target', 'blank');
document.body.appendChild(link);
link.click();
}
function toDataURL(url) {
return fetch(url)
.then((response) => {
return response.blob();
})
.then((blob) => {
return URL.createObjectURL(blob);
});
}
<input id="url" value="https://images.pexels.com/photos/1741205/pexels-photo-1741205.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"/>
<button onclick="downloadFile('test')">Download</button>
虽然这个问题很老,但没有一个答案是可行的。据我所知,所有文件首先加载到内存中,然后保存。这样我们:
- 导致滞后,为此必须实现自定义加载。
- 将文件加载到内存中,这意味着对于大文件,浏览器将崩溃。
- 请勿使用已实现的浏览器下载功能。
前端足够简单(Angular 12(:
downloadFile(url: string, fileName: string): void {
const downloadLink = document.createElement('a');
downloadLink.download = fileName;
downloadLink.href = url;
downloadLink.click();
}
在后端 (.NET 6( 上,我们需要处理流并写入响应正文:
public void Get(string fileId)
{
var fileName = fileService.GetFileName(fileId);
var fileContentType = fileService.GetFileContentType(fileId);
this.Response.Headers.Add(HeaderNames.ContentType, fileContentType);
this.Response.Headers.Add(HeaderNames.ContentDisposition, $"attachment; filename='"{fileName}'"");
fileService.GetFile(Response.Body, fileId);
}
可以从数据库(如果将文件信息保存在其中(或文件系统中检索文件内容类型和名称。内容类型从扩展中分析。
我像这样写到流:
public void GetFile(Stream writeStream, string fileId)
{
var file = GetFileInfo(fileId);
try
{
var fileStream = File.OpenRead(file.FullName);
byte[] buffer = new byte[32768];
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
writeStream.Write(buffer, 0, read);
}
writeStream.Flush();
}
catch (Exception e)
{
throw new CustomException($"Error occured while reading the file. Inner Exception Message: ({e.Message}) Stack Trace: ({e.StackTrace})", ErrorCode.FileReadFailure, e);
}
}
请记住,出于演示目的,我已经简化了我的实现,因此尚未对其进行测试。
我找到的答案要么不适用于 Angular 13.1 和/或不必要的复杂(如公认的示例(,但没有解释为什么这是必要的。对于像 Angular 这样不断变化的生态系统来说,要求附加版本号会很有用。
用户@Aleksandar Angelov 提供的迷你代码段绕过了会话系统,因此需要不必要的授权。
根据他的回答,我想出了以下代码:
downloadConfiguration(url: string, filename: string) {
this.http.get(url, {responseType: 'blob'})
.subscribe(data => {
// console.log("data", data);
var url = window.URL.createObjectURL(data);
let downloadLink = document.createElement('a');
downloadLink.href = url
downloadLink.setAttribute('download', filename);
downloadLink.click();
});
}
如果仅将参数发送到 URL,则可以通过以下方式执行此操作:
downloadfile(runname: string, type: string): string {
return window.location.href = `${this.files_api + this.title +"/"+ runname + "/?file="+ type}`;
}
在接收参数的服务中
- 以ECMAScript 5及更高版本为目标时,八进制文字不可用
- 如何在ie7或更高版本中设置密码字段的占位符
- 有没有一种方法可以使用已经过时的jquery的Filtrify和需要更高版本jquery的bootstrap
- 使用JQuery和IE在悬停时高亮显示表行-所有版本
- Angular 1.2 到 1.3(或更高版本)形式 removeControll 和 addControll 问题
- 是否还需要更多(从高图表版本 4.0.4 开始)
- 如何让原生 WebSocket 在 Android 4.03 及更高版本中工作
- 如何添加指向 Fancybox 的链接以下载图像的高分辨率版本
- 使用 gzip 压缩大文件 - IE8 及更高版本
- 如何下载具有 Angular2 或更高版本的文件
- 如何使用 javascript 针对 IE9 及更高版本
- 如何在谷歌浏览器(v38及更高版本)/firefox(v33及更高版本)中使用Javascript关闭窗口
- 如何在 Angular 1.4 及更高版本中使用 ng-class 和 ng-options
- Angularjs 将空的 JSON 发送到服务器(仅在 IE 9 及更高版本中)
- 无法使用jQuery 1.9.1及更高版本上传ajax文件
- 使用JavaScript检测iOS 5或更高版本
- 代码适用于jquery 1.8.3,但不适用于1.9.1及更高版本
- 如何在Node.js0.11.8及更高版本中使用tlsSocket.regregate(选项、回调)
- 为android中的phonegap 2.3或更高版本解压缩插件
- jQuery脚本不适用于更高版本