Home > Net >  Why local file is showing corrupted after downloading using javascript?
Why local file is showing corrupted after downloading using javascript?

Time:04-24

Good Afternoon,
Scenario: I am having pdf's file on local system and when user click the button, I want it to get downloaded. But after getting download the file on opening shows corrupted. While posting this query I notice the file which is getting download is of 1KB and original file size is 28KB. I didn't understand why ?
I am creating the excel file at backend and saving at user location as due to huge data it is taking a lot of time so once file is created, the user can download the file.

Below are the codes of JS .

function download() {
        var filename="output.pdf";
        var element = document.createElement('a');
        var fileloc="C:\\ebooks\\PDF\\abc.pdf";
        element.setAttribute('href','data:text/plain;charset=utf-8, '   
        encodeURIComponent(fileloc));
        element.setAttribute('download', filename);
        document.body.appendChild(element);
        element.click();
  }

Original file is good. Please correct me what I am doing it wrong .

CodePudding user response:

The data: scheme URL you are creating resolves to a plain text document (not a PDF) containing the text C:\ebooks\PDF\abc.pdf.

You are saving this file with a .pdf extension so when you try to open it, your PDF reader tries to read it as a PDF (which it isn't).

If you want to save the contents of the file at the path you specified then you need to:

Have the user select the file using a <input type="file"> (because JS is not allowed access to files on the user's disk unless they select them explicitly and generating the URL using the FileReader.readAsDataURL() method.


If you are creating the file on the server, as you said, then there is no need to construct a data: scheme URL, you can just use the https: scheme URL that points to the file on the server.

  • Related