Maison  >  Article  >  interface Web  >  Comment télécharger un fichier avec Window.fetch() et gérer l’autorisation ?

Comment télécharger un fichier avec Window.fetch() et gérer l’autorisation ?

Barbara Streisand
Barbara Streisandoriginal
2024-10-23 07:32:01612parcourir

How to Download a File with Window.fetch() and Handle Authorization?

Téléchargement d'un fichier avec window.fetch()

Lorsque vous essayez de télécharger un fichier à l'aide de window.fetch(), les étapes appropriées à suivre dans le bloc then sont comme suit :

.then((response) => {
  // Convert the response to a blob.
  return response.blob();
})
.then((blob) => {
  // Create a URL for the downloaded file.
  const fileURL = URL.createObjectURL(blob);

  // Navigate to the file URL to start downloading the file.
  window.location.assign(fileURL);
});

Pour une solution plus concise et efficace utilisant uniquement l'API fetch, considérez le code suivant :

const url ='http://sample.example.file.doc'
const authHeader ="Bearer 6Q************" 

const options = {
  headers: {
    Authorization: authHeader
  }
};
 fetch(url, options)
  .then( res => res.blob() )
  .then( blob => {
    var file = window.URL.createObjectURL(blob);
    window.location.assign(file);
  });

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn