0

I don't know very much Javascript, but I am building this online task for a psychology experiment. The task involved subjects to go through this javascript "application" (or whatever I should call it). At one point, I need a .docx to be downloaded on their computer via a line of code. I am wondering how to do this.

I figured the answer to this would be easy to find online, but it is not. All the resources I can find describe building a button or an HTML thing that causes a file to be downloaded, but I need this download to be triggered via a line of code within a function that is already running. (I already have the .docx saved online. I am not trying to live generate the .docx using the .js code).

Any suggestions?

I tried using this download.js code, but I couldn't get it to work. When I do something like the code below, it just downloads a .txt file called "file_name.txt" where the text is "/filepath.docx/"

download('/filepath.docx', 'file_name', 'test')

Any help would be much appreciated. Also, I know even less about HTML.

Thank you

I think I found a solution:

var a = document.createElement('A');
var filePath = 'file_path.docx;
a.href = filePath;
a.download = filePath.substr(filePath.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

I found this solution on StackOverflow here and here.

1 Answers1

0

I think the problem is with the third parameter of the download function which is the MineType. since it is a .docx, you may let the brower detect the type by call it like this:

download('/filepath.docx', 'file_name.docx');

Took from documentation of download.js

strMimeType The MIME content-type of the file to download. While optional, it helps the browser present friendlier information about the download to the user, encouraging them to accept the download.

Patrissol Kenfack
  • 764
  • 1
  • 8
  • 22