首页 > 解决方案 > HttpRequest 文件下载 下载没有扩展名的文件

问题描述

我还是 Angular 的新手,我们有一个与下载文件相关的错误 - 其中一个页面有一个网格,其中包含单击时下载到 PC 的文件。然而,当文件被奇怪地下载时,像这样:

在此处输入图像描述

我不明白这是什么格式。例如,我上传了一个 .pdf 文件,当它下载文件并尝试打开它时,Windows 会询问我要使用哪个程序打开它。这些文件不会损坏,因为我可以使用正确的程序打开它们,但如果文件是 PDF 或 TXT,我希望它完全像那样下载。我们使用相同的方法在主 ASP.NET Web 应用程序中保存和下载文件,并且所有文件都在那里正常下载。

保存文件:

this.dataService
            .saveItemAndGetId('api/documents-medicine/save', data)
            .finally(() => {
                this.loaderR = false;
                this.addNewResolved.emit(true);
                this.removeClickedElement();
            })
            .subscribe(
            res => this.sharedService.handleSaveResponse(res > 0 ? true : false, this.localization.translate('documents'), '/app/documents/' + this.sharedService.globals.selectedResident.id),
            err => this.sharedService.handleError(err)
            );

文件下载:

this.dataService
            .getFile('api/documents-medicine/' + data[1].id)
            .subscribe(
            res => window['saveAs'](res, data[1].fileName),
            err => this.sharedService.handleError(err)
            )

.getFile 服务:

DocumentModel model = this.repository.getResidentSingleDocument(id);
        if (model != null)
        {
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(model.DocumentData);
            return result;
        }

        return new HttpResponseMessage(HttpStatusCode.BadRequest);

存储库中的“getResidentSingleDocument”方法:

try
        {
            return this.ctx.ResidentDocuments.Where(it => it.ID == Id)
                .Select(it => new DocumentModel
                {
                    Title = it.Titel,
                    DocumentData = it.ResidentDocument,
                    CreatedBy = it.CreatedBy
                }).SingleOrDefault();
        }
        catch (Exception Ex)
        {
            throw Ex;
        }

标签: angular

解决方案


文件名应在后端设置。

result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "foo.txt"
};

此处的客户端解决方案: 是否有任何方法可以在使用数据时指定建议的文件名:URI?


推荐阅读