How to handle file downloads with JWT based authentication?

前端 未结 5 743
北荒
北荒 2020-12-07 07:24

I\'m writing a webapp in Angular where authentication is handled by a JWT token, meaning that every request has an \"Authentication\" header with all the necessary informati

5条回答
  •  难免孤独
    2020-12-07 08:12

    Here's a way to download it on the client using the download attribute, the fetch API, and URL.createObjectURL. You would fetch the file using your JWT, convert the payload into a blob, put the blob into an objectURL, set the source of an anchor tag to that objectURL, and click that objectURL in javascript.

    let anchor = document.createElement("a");
    document.body.appendChild(anchor);
    let file = 'https://www.example.com/some-file.pdf';
    
    let headers = new Headers();
    headers.append('Authorization', 'Bearer MY-TOKEN');
    
    fetch(file, { headers })
        .then(response => response.blob())
        .then(blobby => {
            let objectUrl = window.URL.createObjectURL(blobby);
    
            anchor.href = objectUrl;
            anchor.download = 'some-file.pdf';
            anchor.click();
    
            window.URL.revokeObjectURL(objectUrl);
        });
    

    The value of the download attribute will be the eventual file name. If desired, you can mine an intended filename out of the content disposition response header as described in other answers.

提交回复
热议问题