练习 - 下载用户文件

已完成

在此练习中,你将完成应用中的下载功能,以便可以选择文件名来下载文件。

  1. 将以下函数添加到 graph.js 文件结尾:

    async function downloadFile(file) {
      try {
        const response = await graphClient
            .api(`/me/drive/items/${file.id}`)
            .select('@microsoft.graph.downloadUrl')
            .get();
        const downloadUrl = response["@microsoft.graph.downloadUrl"];
        window.open(downloadUrl, "_self");
      } catch (error) {
        console.error(error);
      }
    }
    
  2. ui.js 中,将此行紧接在 a.href = assignment 语句后面:

    a.onclick = () => { downloadFile(file); };
    

    完成的 displayFiles() 函数应如下所示:

    async function displayFiles() {
      const files = await getFiles();
      const ul = document.getElementById('downloadLinks');
      while (ul.firstChild) {
        ul.removeChild(ul.firstChild);
      }
      for (let file of files) {
        if (!file.folder && !file.package) {
          let a = document.createElement('a');
          a.href = '#';
          a.onclick = () => { downloadFile(file); };
          a.appendChild(document.createTextNode(file.name));
          let li = document.createElement('li');
          li.appendChild(a);
          ul.appendChild(li);
        }
      }
    }
    
  3. 现在刷新页面。 你应该可以选择一个文件来下载它。