简体   繁体   English

如何在Angular上创建下载文件服务?

[英]How can I create a download file service on Angular?

I create a controller in my .Net Core API in order to create a file with package nugget iTextSharp and send the pdf file to the user. 我在.Net Core API中创建了一个控制器,目的是使用软件包nugget iTextSharp创建一个文件,并将pdf文件发送给用户。 When I test it with Swagger cause it's implemented in the project it's work well but it's doesn't work when I want to use the controller in my angular application. 当我使用Swagger进行测试时,因为它已在项目中实现,因此效果很好,但是当我想在我的角度应用程序中使用控制器时,它就无法工作。

My C# controller : 我的C#控制器:

[HttpPost("[Action]")]
public IActionResult CreateLicensePDF(License license) { 
    GenerateLicenseFIleService generateLicenseFIleService = new GenerateLicenseFIleService();
    byte[] abytes = generateLicenseFIleService.Generate(license);
    string fileName = license.Customer.CustomerNumber + "-" + license.Order.OrderNumber + ".pdf";
    return File(abytes, "application/pdf", fileName);
}

The service which call the api url to execute the controller in my angular application : 调用api url以在我的angular应用程序中执行控制器的服务:

generateLicensePDF(license){
    return this.http.post(`${this.config.catchApiUrl()}GenerateFile/CreateLicensePDF`,license);

}

On click on a button it execute this function to call the service 单击按钮后,它将执行此功能以调用服务

onSubmit(){
    // get a license by id and it's return license's data
    this.licenseInfoService.getLicenseById(1).subscribe(

    r => {// call the service which download the file
        this.licenseInfoService.generateLicensePDF(r).subscribe(

            r => console.log("yeah"),
            err => console.log(err))

   }

}

I try lot of thing but the error is always : 我尝试了很多事情,但错误始终是:

it's return an HttpErrorMessage, the status is 400 with this error message 它返回一个HttpErrorMessage,此错误消息的状态为400

"": ["The input was not valid. “”:[“输入无效。

or : 要么 :

it's return an HttpErrorMessage, the status is 200 with this error message 它返回一个HttpErrorMessage,此错误消息的状态为200

SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad SyntaxError:JSON中意外的令牌%在XMLHttpRequest.onLoad的JSON.parse()位置0

How about setting responseType : 如何设置responseType

generateLicensePDF(license){
    return this.http.post(`${this.config.catchApiUrl()}GenerateFile/CreateLicensePDF`,license, { responseType: 'blob' });
}

Then you can install Angular FileSaver : 然后,您可以安装Angular FileSaver

npm install file-saver --save

And then: 接着:

import { saveAs } from 'file-saver';

onSubmit(){
    // get a license by id and it's return license's data
    this.licenseInfoService.getLicenseById(1).subscribe(

    r => {// call the service which download the file
        this.licenseInfoService.generateLicensePDF(r).subscribe(
            x => {
                saveAs(x);
                console.log("yeah")
            },
            err => console.log(err))
   }
}

And that will get you a Blob result from service and with saveAs you will download it on your machine. 这样一来,您便可以通过服务和saveAs获得Blob结果,然后将其下载到计算机上。 If you want to get a response with a file you can use: 如果要获得文件响应,可以使用:

this.http.post(`${this.config.catchApiUrl()}GenerateFile/CreateLicensePDF`,license, { observe: 'response', responseType: 'blob' });

and then you can save file with: 然后您可以使用以下方法保存文件:

saveAs(r.body)

I hope this helps... 我希望这有帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 angular 6 中下载 excel 文件 - How can I download an excel file in angular 6 生成后如何下载NuGet作为.csproj文件的一部分,以便创建.nupkg文件? - How can I download NuGet after build as part of a .csproj file so that I can create a .nupkg file? 我是否可以创建一个流式传输pdf以供下载的Web服务 - Can I create a web service that streams a pdf for download Windows服务:如何将多个Windows服务创建为多个exe文件 - Windows Service: How can i create multiple windows service as a multiple exe file 如何创建允许用户通过Web浏览器连接到我的服务并上传文件的WCF服务? - How can I create a WCF service that allows users to connect to my service through a web browser and upload a file? 如何使用 webview 下载 xamarin 中的文件? - How can I download file in xamarin with webview? 如何动态创建文件并将其提供给用户(单击下载按钮)? C# - How can I dynamically create and serve a file to a user (on click of a download button)? C# 如何将 Excel 文件下载到用户的下载文件夹? - How can I download an Excel file to the user's download folder? 如何在 asp.net 中创建下载按钮? - how can i create download button in asp.net? 如何在不使用“文件下载”对话框的情况下使用 WebBrowser 控件下载文件? - How can I download a file using a WebBrowser control without using the File Download dialog box?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM