简体   繁体   中英

JavaScript Prompt download in browser

Im simply trying to download a file from the server and prompt the download in the browser for the user to see.

What i have right now: Client

export function downloadTemplateAction(questionnaire) {
  return dispatch => {
    dispatch(downloadTemplateRequestAction(questionnaire));

    return request
      .get(downloadGETUrl)
      .end((err, res) => {
        if (err) {
          console.log("Download ERROR", err)
          dispatch(downloadTemplateFailureAction(err, questionnaire));
        } else {
          console.log("Download Success", res.body)
          dispatch(downloadTemplateSuccessAction(res.body, questionnaire));
        }
      });
  }
}

Server:

export function downloadTemplateDocument(req, res){
    res.download('template/Example.docx');
    res.end();
}

Im facing two problems:

First : When trying to download the file via the function of the Client, the response body is null but success and nothing more happens.

Second : When contacting the get API via the browser localhost:3002/api/download, the download works but the received file is empty. There should be text in it.

What am i doing wrong here?

Browser can't prompt a download progress because your request is sent via XMLHttpRequest. Physical access to the file is needed for the browser to be aware of any download.

You could use download attribute to tell browser to download linked ressource.

original answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM