Sending an Excel file from backend to frontend and download it at the frontend

故事扮演 提交于 2020-01-25 08:00:05

问题


I had created an Excel file at the backend (Express JS) using Exceljs npm module. I have it stored in a temp directory. Now I would want to send the file from the back-end to the front-end and download it there when the user clicks a button. I am struck on two things 1. How to send the file from the backend to the frontend through an HTTP POST request 2. How to then download the file in the front-end

Edited content:

I need the front end to be a button that appends the file to it and then download it. This is how my code looks, I am not getting the file properly from the backend to the front-end

front end file:

 function(parm1,parm2,parm3){
 let url =${path}?parmA=${parm1}&parmB=${parm2}&parmC=${parm3};
 let serviceDetails = {};
 serviceDetails["method"] = "GET";
 serviceDetails["mode"] = "cors";
 serviceDetails["headers"] = {
 "Content-Type": "application/json"
 };

fetch(url, serviceDetails)
  .then(res => {
    if (res.status != 200) {
      return false;
    }
    var file = new Blob([res], { type : 'application/octet-stream' });
    a = document.createElement('a'), file;
    a.href = window.URL.createObjectURL(file);
    a.target = "_blank"; 
    a.download = "excel.xlsx";
    document.body.appendChild(a);
    a.click(); 
    document.body.removeChild(a); 

  }).catch(error => {
     return false;
  });

}`

router.js

var abc = ... // this is a object for the controller.js file
router.get('/path', function(req, res) {
abc.exportintoExcel(req, res);
});

controller.js

let xyz = ... //this is a object for the service.js file
 exports.exportintoExcel = function(req, res) {
 xyz.exportintoExcel(reqParam,res);
 }

service.js

exportintoExcel(req,response){
       //I have a excel file in my server root directory
        const filepath = path.join(__dirname,'../../nav.txt');
        response.sendFile(filepath);
    })
}

回答1:


This is a complete re-write of an earlier answer, so sorry if anyone needed that one, but this version is superior. I'm using a project created with express-generator and working in three files:

  • routes/index.js
  • views/index.ejs
  • public/javascripts/main.js

index.ejs

Start with an anchor tag that has the download attribute, with whatever filename you wish, and an empty href attribute. We will fill in the href in the main.js file with an ObjectURL that represents the Excel file later:

<body>
  <a id="downloadExcelLink" download="excelFile.xlsx" href="#">Download Excel File</a>
  <script type="text/javascript" src="/javascripts/main.js"></script>
</body>

public/javascripts/main.js

Select the anchor element, and then make a fetch() request to the route /downloadExcel. Convert the response to a Blob, then create an ObjectURL from this Blob. You can then set the href attribute of the anchor tag to this ObjectURL:

const downloadExcelLink = document.getElementById('downloadExcelLink');

(async () => {
  const downloadExcelResponse = await fetch('/downloadExcel');
  const downloadExcelBlob = await downloadExcelResponse.blob();
  const downloadExcelObjectURL = URL.createObjectURL(downloadExcelBlob);
  downloadExcelLink.href = downloadExcelObjectURL;
})();

routes/index.js

In the index router, you simply need to call the res.sendFile() function and pass it the path to the Excel file on your server.

router.get('/downloadExcel', (req, res, next) => {
  const excelFilePath = path.join(__dirname, '../tmp/excel.xlsx');
  res.sendFile(excelFilePath, (err) => {
    if (err) console.log(err);
  });
});

That's it! You can find a git repo here of the project. Clone into it and try it out for yourself if you can't get this code to work in your project as it is.

How It Works

When the page loads, 4 requests are fired off to our server, as we can see in the console output:

GET / 200 2.293 ms - 302
GET /stylesheets/style.css 200 1.123 ms - 111
GET /javascripts/main.js 200 1.024 ms - 345
GET /downloadExcel 200 2.395 ms - 4679

The first three requests are for index.ejs (/), the CSS stylesheet, and our main.js file. The fourth request is sent by our call to fetch('/downloadExcel') in the main.js file:

const downloadExcelResponse = await fetch('/downloadExcel');

I have a route-handler setup in routes/index.js at this route that uses res.sendFile() to send a file from our filesystem as the response:

router.get('/downloadExcel', (req, res, next) => {
  const excelFilePath = path.join(__dirname, '../tmp/excel.xlsx');
  res.sendFile(excelFilePath, (err) => {
    if (err) console.log(err);
  });
});

excelFilePath needs to be the path to the file on YOUR system. On my system, here is the layout of the router file and the Excel file:

/
/routes/index.js
/tmp/excel.xlsx

The response sent from our Express server is stored in downloadExcelResponse as the return value from the call to fetch() in the main.js file:

const downloadExcelResponse = await fetch('/downloadExcel');

downloadExcelResponse is a Response object, and for our purposes we want to turn it into a Blob object using the Response.blob() method:

const downloadExcelBlob = await downloadExcelResponse.blob();

Now that we have the Blob, we can call URL.convertObjectURL() to turn this Blob into something we can use as the href for our download link:

const downloadExcelObjectURL = URL.createObjectURL(downloadExcelBlob);

At this point, we have a URL that represents our Excel file in the browser, and we can point the href to this URL by adding it to the DOM element we selected earlier's href property:

When the page loads, we selected the anchor element with this line:

<a id="downloadExcelLink" download="excelFile.xlsx" href="#">Download Excel File</a>

So we add the URL to the href here, in the function that makes the fetch request:

downloadExcelLink.href = downloadExcelObjectURL;

You can check out the element in the browser and see that the href property has been changed by the time the page has loaded:

Notice, on my computer, the anchor tag is now:

<a id="downloadExcelLink" download="excelFile.xlsx" href="blob:http://localhost:3000/aa48374e-ebef-461a-96f5-d94dd6d2c383">Download Excel File</a>

Since the download attribute is present on the link, when the link is clicked, the browser will download whatever the href points to, which in our case is the URL to the Blob that represents the Excel document.

I pulled my information from these sources:

  • JavaScript.info - Blob as URL
  • Javascript.info - Fetch

Here's a gif of how the download process looks on my machine:




回答2:


OK, now that I see your code, I can try and help out a little. I have refactored your example a little bit to make it easier for me to understand, but feel free to adjust to your needs.

index.html

I don't know what the page looks like that you're working with, but it looks like in your example you are creating an anchor element with JavaScript during the fetch() call. I'm just creating one with HTML in the actual page, is there a reason you can't do this?

<body>
  <a id="downloadLink" download="excel.xlsx" href="#">Download Excel File</a>
  <script type="text/javascript" src="/javascripts/test.js"></script>
</body

With that in hand, here is my version of your front end JS file:

test.js

const downloadLink = document.getElementById('downloadLink');

sendFetch('a', 'b', 'c');

function sendFetch(param1, param2, param3) {

  const path = 'http://localhost:3000/excelTest';
  const url = `${path}?parmA=${param1}&parmB=${param2}&parmC=${param3}`;
  const serviceDetails = {};
  serviceDetails.method = "GET";
  serviceDetails.mode = "cors";
  serviceDetails.headers = {
    "Content-Type": "application/json"
  };

  fetch(url, serviceDetails).then((res) => {
    if (res.status != 200) {
      return false;
    }
    res.blob().then((excelBlob) => {
      const excelBlobURL = URL.createObjectURL(excelBlob);
      downloadLink.href = excelBlobURL;
    });
  }).catch((error) => {
     return false;
  });
}

I had to fill in some details because I can't tell what is going on from your code. Here are the things I changed:

  1. Selected the DOM element instead of creating it:

Your version:

a = document.createElement('a'), file;

My version:

index.html

<a id="downloadLink" download="excel.xlsx" href="#">Download Excel File</a>

test.js

const downloadLink = document.getElementById('downloadLink');

This saves us the trouble of creating the element. Unless you need to do that for some reason, I wouldn't. I'm also not sure what that file is doing in your original.

  1. Name the function and change parm -> param for arguments list

Your version:

function(parm1,parm2,parm3){

My version:

function sendFetch(param1, param2, param3) {

I wasn't sure how you were actually calling your function, so I named it. Also, parm isn't clear. Param isn't great either, should describe what it is, but I don't know from your code.

  1. Create a path variable and enclose url assignment in backticks

Your version:

let url =${path}?parmA=${parm1}&parmB=${parm2}&parmC=${parm3};

My version:

const path = 'http://localhost:3000/excelTest';
const url = `${path}?parmA=${param1}&parmB=${param2}&parmC=${param3}`;

In your version, that url assignment should throw an error. It looks like you want to use string interpolation, but you need backticks for that, which I added. Also, I had to define a path variable, because I didn't see one in your code.

  1. Cleaned up some formatting

I used 'dot' notation for the serviceDetails, but that was just personal preference. I also changed the spacing of the fetch() call, but no need to reprint that here. Shouldn't effect anything.

  1. Create a blob from the fetch response

Your version:

var file = new Blob([res], { type : 'application/octet-stream' });

My version:

res.blob().then((excelBlob) => {

I'm not sure why you are calling the Blob constructor and what that [res] is supposed to be. The Response object returned from fetch() has a blob() method that returns a promise that resolves to a Blob with whatever MIME-type the data was in. In an Excel documents case, this is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

  1. Create an ObjectURL from the Blob and add this URL to the href of the anchor tag.

Your version:

a = document.createElement('a'), file;
a.href = window.URL.createObjectURL(file);
a.target = "_blank"; 
a.download = "excel.xlsx";
document.body.appendChild(a);
a.click(); 
document.body.removeChild(a);

My version:

const excelBlobURL = URL.createObjectURL(excelBlob);
downloadLink.href = excelBlobURL;

You have to do a bunch of DOM manipulation, which I'm not sure why you need. If you do have to dynamically create this element, then I'm not sure why you are 'clicking' it, then removing it, if the user is supposed to be able to click it. Maybe clarify for me why you are doing this, or if you really need to do it. Either way, in my version I create the ObjectURL and then assign it, but you could just as easily not store it in a variable.

  1. Call the function that sends the fetch request.

As my function signature is:

function sendFetch(param1, param2, param3)

I needed to call it somewhere in order to fire off the request, so I did so like this:

sendFetch('a', 'b', 'c'); 

Right when the page loads, as you can see from the server logs:

GET / 304 0.448 ms - -
GET /javascripts/test.js 304 1.281 ms - -
GET /excelTest?parmA=a&parmB=b&parmC=c 304 0.783 ms - -

The first two requests are for the index.html page and the test.js file, then the fetch request is fired with the param's I passed in. I'm not sure how you are doing this in your app, because that is not included in your code.

Everything I just covered is Front-End. I'm assuming your server-side code is actually sending an excel file with your call to response.sendFile() in service.js. If you are sure that the file is getting sent, then the code I've given you should work, when adjusted to your app.

So, in conclusion, what this code does is:

  1. Load an HTML page with an anchor tag with no href attribute set.
  2. Send off a fetch() request to the server.
  3. Turn the fetch response into a Blob, then create an ObjectURL from this Blob.
  4. Assign that ObjectURL to the anchor tag's href attribute.

When the user clicks the 'Download Excel File' link, the Excel sheet should be downloaded. If you didn't want them to see the link until after the fetch request, you could definitely do create the anchor tag in JS instead, let me know if you want to see how to do that.

As before, here is a gif showing how it looks on my machine (this is with your version and my modifications):



来源:https://stackoverflow.com/questions/58923772/sending-an-excel-file-from-backend-to-frontend-and-download-it-at-the-frontend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!