I had an endpoint on .Net server

[HttpPost]
[Route("api/tagExportSelectedToExcel")]

and a React frontend with axios. The task was to add a button which downloads a file from this API. I spent several hours before found this solution. I hope it will be helpful for someone else.

This is what I did:

axios('/api/tagExportSelectedToExcel', {
    data: exportFilter,
    method: 'POST',
    responseType: 'blob'
}).then(res => resolveAndDownloadBlob(res));

Where resolveAndDownloadBlob:

/**
 * Resolved and downloads blob response as a file.
 * FOR BROWSERS ONLY
 * @param response
 */
function resolveAndDownloadBlob(response: any) {
    let filename = 'tags.xlsx';
    filename = decodeURI(filename);
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    window.URL.revokeObjectURL(url);
    link.remove();
}
Answer from Michael Klishevich on Stack Overflow
🌐
Medium
medium.com › @peterkwidjaja › downloading-files-with-rest-api-9c02bab8869a
Downloading Files with REST API. One of the features that I have to… | by Peter Kristianto Widjaja | Medium
July 23, 2018 - { "filename": <filename>, "data": <Base64 String of the file> } On front-end side, what we need is to download it using the anchor tag. Assuming res variable refers to the response from the server as above.
Discussions

javascript - Implement file download from REST service in webapp - Stack Overflow
I have a simple webapp which I intend to serve a file download from a REST api. The file is of type .xlsx. My naive attempt to accomplish this uses a design pattern that I have copied from other ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Get File and download from rest api - Stack Overflow
On click on download button I need to "GET" an xml file from rest api url (http://localhost:xxxx/xx.xml) and save it on users desktop. How do I achieve this in javascript. Thanks. More on stackoverflow.com
🌐 stackoverflow.com
August 7, 2012
jquery - How to download a file from a RESTful API? - Stack Overflow
I defined a part of my RESTful API to return a JSON or Excel list of data, based on the Accept in the request. For the JSON version it is easy to use with Ajax (jQuery): $.ajax({ url: api.... More on stackoverflow.com
🌐 stackoverflow.com
May 13, 2017
sharepoint server - Download file using REST - SharePoint Stack Exchange
I want to download a file using REST API. I have a file in a document library /folder. I want download that file, but with a different name. Edit 1 : Below is my code. i am able to download file... More on sharepoint.stackexchange.com
🌐 sharepoint.stackexchange.com
🌐
Stack Overflow
stackoverflow.com › questions › 43955332 › how-to-download-a-file-from-a-restful-api
jquery - How to download a file from a RESTful API? - Stack Overflow
May 13, 2017 - Great, now there are some dupes to your question if you can afford modern browsers that support the HTML5 File API: stackoverflow.com/questions/16086162/… stackoverflow.com/questions/24501358/… If you need to support legacy browsers your only bet is to add a query string parameter to your GET endpoints allowing to perform the content negotiation and then use an anchor or window.location=...
🌐
Gitbrent
gitbrent.github.io › SpRestLib › blog › 2018 › 11 › 17 › download-sharepoint-file-using-javascript.html
Downloading a file from SharePoint library using JavaScript and REST API · SpRestLib
// Example: Client-browser code to download file from SharePoint using JavaScript and REST sprLib.file('SiteAssets/img/sprestlib.png').get() .then(function(blob){ var url = (window.URL || window.webkitURL).createObjectURL(blob); var link = document.createElement("a"); link.setAttribute("href", url); link.setAttribute("download", _fileName); link.style = "visibility:hidden"; document.body.appendChild(link); link.click(); setTimeout(function(){ document.body.removeChild(link); }, 500); }); See File API for a working demo.
Find elsewhere
🌐
GitHub
gist.github.com › Akhu › f164de7aa523e1e8856c3756b50f4e75
Download File with JS from REST API.html · GitHub
Download File with JS from REST API.html · This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ·
Top answer
1 of 4
1

I usually use AttachmentFiles endpoint to do this, it is provided when you create or select Item with API.

<link  rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/AttachmentFiles" type="application/atom+xml;type=feed" title="AttachmentFiles" href="Web/Lists(guid'12f9fd2c-0eea-4440-b9d3-a6e445839ba3')/Items(66)/AttachmentFiles" />

Main part is

href="Web/Lists(guid'12f9fd2c-0eea-4440-b9d3-a6e445839ba3')/Items(66)/AttachmentFiles" 

You can use both

To download      /Items(66)/AttachmentFiles('file.docx')
To upload        /Items(66)/AttachmentFiles/add(FileName='file.docx')

Then u can use a GET method to download file content :

executor.executeAsync(
    {
        url: UsePreviousEndPoint,
        type: "GET",
        contentType: "application/atom+xml;type=entry",
        headers: {
                "Accept": "application/atom+xml",
                "Authorization": "Bearer " + UserOrAppToken
            },      
        success: function (blobURL)
        {
            SaveToDisk_blob(blobURL, fileName)
        },
        error: function (xhr)
        {
            console.log(xhr);
            console.log("downloadFile" + xhr.status + ": " + xhr.statusText);

        }
    });

I guess Digest is only mandatory for POST request.

2 of 4
1

below are my final working code for downloading file from REST.

var dfd = $.Deferred();
var xhr = new XMLHttpRequest();
xhr.open("GET", filepath);
xhr.responseType = "blob";
//setting response-type header to be blob so that we get the file as blob
xhr.onload = function ()
{
//async call
var blobobj = xhr.response;
window.navigator.msSaveBlob(blobobj, fileName);
//save using msSaveBlob.
dfd.resolve(true);
}
xhr.send();
return dfd.promise()
🌐
Mastertheboss
mastertheboss.com › home › jboss frameworks › resteasy › using rest services to upload and download files
Using REST Services to upload and download files - Mastertheboss
May 24, 2024 - Finally, click Send to upload the File from Postman. Firstly, create the following index.jsp page which uses an AngularJS Controller to interact with our REST Service: <html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <link rel="stylesheet" type="text/css" href="stylesheet.css" media="screen" /> <script type = "text/javascript"> angular.module('app', []) .controller('ctrl', function ($scope, $http) { $scope.files = []; $scope.loadData = function () { $http({ method: 'GET', url: '/rest-file-manager/rest/file/list' }).then(function successCallba
🌐
Reddit
reddit.com › r/nextjs › is there a 'best practice' for downloading files from an api response?
r/nextjs on Reddit: Is there a 'best practice' for downloading files from an API response?
November 6, 2023 -

I'm working with an API res that contains a zip, csv, and pdf. I've been researching how I should download and/or create download buttons for these files but a lot of articles I'm looking through specify that their method is 'hacky' (or something similar).

I don't like the idea of pushing a 'hacky' solution to production. It may be a starting point but not really a good foundation to build off of. Does anybody know of good practices for this kind of procedure?

I've boiled it down to:

  1. Parse the response

  2. Store the file contents

  3. Create sources for the downloads

but surely it isn't that simple, right?

🌐
GitHub
github.com › bezkoder › node-js-express-download-file
GitHub - bezkoder/node-js-express-download-file: Node.js Download File with Express Rest APIs example · GitHub
Node.js Download File example with Express Rest API · Node.js Express File Upload Rest API example · Front-end Apps to work with this Node.js Server: Angular 8 Client / Angular 10 Client · Vue Client / Vuetify Client · React Client / React Hooks Client ·
Starred by 13 users
Forked by 16 users
Languages   JavaScript
🌐
CodeSignal
codesignal.com › learn › courses › efficient-api-interactions-with-javascript › lessons › downloading-files-from-an-api-using-javascript
Downloading Files from an API Using JavaScript
GET requests are fundamental for retrieving files from an API. When you send a GET request using fetch, your client communicates with the server at a specified URL, asking it to provide the file. The server responds with the file data, if available and permissible, along with an HTTP status code (like 200 OK). Here's a basic example of downloading a file named welcome.txt from our API at http://localhost:8000/notes.
🌐
Medium
medium.com › @khushbooverma8319 › download-api-file-in-frontend-91bd51e4ee19
Download file in frontend getting from API | by Khushbooverma | Medium
May 22, 2023 - Suppose we have a button on click of which we want to download the CSV file. We have a onClick handler named handlDownload as shown below. const handleDownload = () => { setLoading(true); API.get('https://sample/api', { responseType: "blob", }) .then((response) => { const url = window.URL.createObjectURL(new Blob([response.data])); console.log(url); var blob = new Blob([response.data], { type: "text/plain;charset=utf-8", }); saveAs(blob, `${response.fileName}.pdf`); setLoading(false); }) .catch((err) => { console.log(err); setLoading(false); }); };
🌐
Oracle
docs.oracle.com › en › cloud › paas › content-cloud › rest-api-documents › op-documents-api-1.2-files-fileid-data-get.html
REST API for Documents - Download File
November 27, 2023 - GET .../files/D34A657B8723A96097F80926T0000000000100000001/data?version=2 ... The following example downloads version 1 of the specified file. If the status code indicates success (200), the response includes a data stream that contains the file contents.
🌐
Medium
medium.com › yellowcode › download-api-files-with-react-fetch-393e4dae0d9e
Download API Files With React & Fetch | by Manny | yellowcode | Medium
April 11, 2020 - The issue with this is that it leaves the location of the document exposed for further download after the initial request, which might not be that much of a problem. The biggest issue with this is that now, on the server side, we have a physical file to manage. It takes up space and will require clean up. This method is the one we’ll be looking at today, where the file data is sent to us via the API, we interpret that data, and download it directly on the client side, without opening up a new tab.
🌐
Filestack
blog.filestack.com › home › react download file from api: a guide
React download file from API: A Guide
July 19, 2023 - When it comes to React download files from API, we have multiple options. We can use Axios for API calls or Fetch API. Axios is essentially a library in React used to send HTTP requests to REST API or API endpoints.
🌐
Stack Overflow
stackoverflow.com › questions › 38902165 › downloading-binary-file-over-rest-api
javascript - downloading binary file over REST API - Stack Overflow
August 11, 2016 - If you need to support all dead browser then you can forget about any javascript solution such as filesaver or any other client side solution solution, that don't even work in todays Safari. The only solution then is to use a server side solution to download things.