使用 HttpClient 和 file-saver.js 下载文件获取 JHipster 应用程序加载页面以及请求的下载文件

Downloading file using HttpClient and file-saver.js fetches JHipster app-loading page as well as requested download file

问题总结:

我正在使用 HttpClient 和 file-saver.js 成功下载从 Spring rest 端点提供的请求文件。但是,保存了具有请求文件名的两个文件(应该只有 1 个)。第一个文件在请求到达 Spring Rest 端点之前就已保存。这是一个 5K 的文件,经检查包含 jhipster app-loading html 页面。一旦来自服务器的请求 returns 将保存第二个具有相同名称的文件,这是请求的实际下载文件。

为什么会这样?请参阅下面的库版本和代码示例:

软件版本:

"@angular/common": "8.2.0",

"@angular/core": "8.2.0",

"文件保护程序": "^2.0.2",

"rxjs": "6.4.0",

下载服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class DownloadsService {
    public resourceUrl = 'api/downloads/';
    constructor(private http: HttpClient) {}

    download(fileId: string): Observable<Blob> {
        const url = this.resourceUrl + fileId;
        return this.http.get(url, {reportProgress: true, responseType: 'blob'});
    }
}

下载组件

import {Component, OnInit} from '@angular/core';
import {faApple, faLinux, faWindows} from '@fortawesome/free-brands-svg-icons';
import {DownloadsService} from './downloads.service';
import * as fileSaver from 'file-saver';

@Component({
    selector: 'jhi-downloads',
    templateUrl: './downloads.component.html',
    styleUrls: ['./downloads.component.css']
})
export class DownloadsComponent implements OnInit {
    
    ... download object defined here with file name and fileid

    termsAccepted = false;

    constructor(private downloads: DownloadsService) {
    }

    ngOnInit() {
    }

    onClick(download) {
        const filename = download.filename;
        const fileId = download.fileId;
        this.downloads.download(fileId)
            .subscribe(blob => {
                fileSaver.saveAs(blob, filename);
            });
    }
}

结果是2个文件:

filename.ext - 这是 jhipster 应用加载 html 页面 (5k)

filename.ext(1) - 这是实际请求的文件 (70.5M)

额外注意:生产模式下的 jhipster 应用程序 运行 部署在 Tomcat 应用程序服务器上。

愚蠢的错误....正在使用 <a> 标签作为下载按钮。更改为 <div> 并且一切如预期。