how to get a pdf file and open in new tab in asp.net core web api?

mc 4,656 Reputation points
2022-08-22T07:46:33.547+00:00

I use a ajax to post a data to the api

the api will return a pdf back but the ajax can not open it.

the response is Content-Disposition: attachment; filename=download.pdf
content-type is application/pdf

but the data is %PDF-1.4 5 0 obj <</Type /Page /Parent 3 0 R /Contents 6 0 R /MediaBox [0 0 595.44 841.68] >> endobj 6 0 obj

such code not a file

my ajax :

$.ajax({  
url:'/api/mypdf',  
type:'POST',  
method:'POST'  
data:{  
json:''//my json data  
},  
success:function(){  
}  

int the api there is a return File(data.ToArray(),'application/pdf','download.pdf');

I need the post data so I can not use window.location.href='/api/mypdf';

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,623 questions
0 comments No comments
{count} votes

Accepted answer
  1. Xinran Shen - MSFT 2,091 Reputation points
    2022-08-23T06:44:23.72+00:00

    Hi, @mc ,

    In your Web Api, I suggest you to return a base64 of type string instead of File or FileStream:

    [HttpPost]  
            public string Post(int id)  
            {  
                //....other code.....  
      
                string fileName = @"C:\Users\Admin\xxxxxx\Test.pdf";  
      
                byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);  
      
                string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);  
                return base64EncodedPDF;  
      
            }  
    

    Then in ajax success function, you can use this code:

    233973-image.png

    233964-new-text-document.txt

    Demo:

    233943-animation.gif

    ------------------------------------------------------------------------------------------------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Xinran Shen


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,941 Reputation points
    2022-08-23T18:49:49.413+00:00

    this will make the download a third larger. if that is an issue, another option is for the server return a url to the Ajax. this would require storing the post data and returning a key to the post data in the url.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.