> ## Documentation Index
> Fetch the complete documentation index at: https://help.dingtalk.io/llms.txt
> Use this file to discover all available pages before exploring further.

# ナレッジベースのファイルをダウンロード

> ナレッジベース内のファイルダウンロードに必要なURLとヘッダー情報をAPIで取得してダウンロードします

本 API を呼び出して、ナレッジベース内のファイルのダウンロード情報を取得します。

## API 呼び出し説明

ダウンロード情報を取得するには、以下の手順を参照してください。

ステップ 1：本 API を呼び出してファイルダウンロード情報を取得し、ファイルのダウンロード URL と headers を入手します。

ステップ 2：ダウンロードを実行します。例を参照してください。

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
public static void main(String[] args) {
  String url = ""; // ダウンロード情報取得 API で取得した internalResourceUrls。
  String path = "/Users/xxxxx/Downloads/test.txt"; // ファイルをダウンロードする目標パス。
  // ダウンロード情報取得 API で取得した headers 情報。
  Map<String, String> headers = "" // ダウンロード情報取得 API で取得した headers。
    OkHttpClient client = new OkHttpClient();
  Request request = new Request.Builder()
    .url(url)
    .headers(Headers.of(headers))
    .build();
  client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
      Sink sink = null;
      BufferedSink bufferedSink = null;
      try {
        File dest = new File(path);
        sink = Okio.sink(dest);
        bufferedSink = Okio.buffer(sink);
        bufferedSink.writeAll(response.body().source());
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (bufferedSink != null) {
          bufferedSink.close();
        }
        if (sink != null) {
          sink.close();
        }
      }
    }
  });
}
```

<Note>
  ファイルサイズが大きい場合は、リソースを分割して取得する必要があります。上記の例に headers フィールドを追加できます：`headers.put("Range","bytes=0-499");`。詳細は [Range を指定して部分コンテンツをダウンロードする](/ja/open/development/use-range-download-a-part-of-content) を参照してください。
</Note>

## リクエスト

### 基本情報

| フィールド       | 値                                                                                               |
| ----------- | ----------------------------------------------------------------------------------------------- |
| HTTP URL    | `https://api.dingtalk.io/v1.0/storage/spaces/{spaceId}/dentries/{dentryId}/downloadInfos/query` |
| HTTP Method | POST                                                                                            |
| 対応アプリタイプ    | appType-社内アプリ                                                                                   |
| 権限要件        | permission-Storage.DownloadInfo.Read-企業ストレージファイルダウンロード情報の読み取り権限                                 |

### リクエストヘッダー

| 名前                          | タイプ    | 必須 | 説明                                                                                                                               |
| --------------------------- | ------ | -- | -------------------------------------------------------------------------------------------------------------------------------- |
| x-acs-dingtalk-access-token | String | 必須 | 本 API を呼び出すためのアクセス認証情報です。[社内アプリのアクセストークンを取得する](/ja/open/development/obtain-the-access-token-of-an-internal-app) API を呼び出して取得します。 |

### パスパラメータ

| 名前       | タイプ    | 必須 | 説明                                                                                                                                                                                                               |
| -------- | ------ | -- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| spaceId  | String | 必須 | スペース ID です。[ノードリストを取得する](/ja/open/development/get-node-list) API を呼び出してナレッジベースノードの `dentryUuid` を取得し、続いて [dentryUuid から spaceId を取得する](/ja/open/development/api-getdentryidbyuuid) API を呼び出して `spaceId` を取得します。  |
| dentryId | String | 必須 | ファイル ID です。[ノードリストを取得する](/ja/open/development/get-node-list) API を呼び出してナレッジベースノードの `dentryUuid` を取得し、続いて [dentryUuid から spaceId を取得する](/ja/open/development/api-getdentryidbyuuid) API を呼び出して `dentryId` を取得します。 |

### クエリパラメータ

| 名前      | タイプ    | 必須 | 説明                                                                                       |
| ------- | ------ | -- | ---------------------------------------------------------------------------------------- |
| unionId | String | 必須 | 操作者の unionId です。[ユーザー詳細を照会する](/ja/open/development/query-user-details) API を呼び出して取得できます。 |

### リクエストボディ

| 名前             | タイプ     | 必須 | 説明                                                                                                                   |
| -------------- | ------- | -- | -------------------------------------------------------------------------------------------------------------------- |
| option         | Object  | 任意 | 任意パラメータです。                                                                                                           |
| version        | Long    | 任意 | ファイルのバージョン番号です。[ファイルバージョンリストを取得する](/ja/open/development/obtains-a-list-of-file-versions) API を呼び出して version を取得できます。 |
| preferIntranet | Boolean | 任意 | イントラネット転送を優先するかどうかです。このパラメータを使用する前提として、専用ストレージのイントラネット転送が設定されている必要があります。   - **true**（デフォルト）：はい - **false**：いいえ      |

### リクエスト例

HTTP

```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
POST /v1.0/storage/spaces/854xxxx/dentries/798xxxxx/downloadInfos/query?unionId=chyxxxxx HTTP/1.1
Host:api.dingtalk.io
x-acs-dingtalk-access-token:xxxxx
Content-Type:application/json

{
  "option" : {
    "version" : 1,
    "preferIntranet" : false
  }
}
```

Java

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * Token を使用してアカウント Client を初期化
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkstorage_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkstorage_1_0.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkstorage_1_0.Client client = Sample.createClient();
        com.aliyun.dingtalkstorage_1_0.models.GetFileDownloadInfoHeaders getFileDownloadInfoHeaders = new com.aliyun.dingtalkstorage_1_0.models.GetFileDownloadInfoHeaders();
        getFileDownloadInfoHeaders.xAcsDingtalkAccessToken = "<your access token>";
        com.aliyun.dingtalkstorage_1_0.models.GetFileDownloadInfoRequest.GetFileDownloadInfoRequestOption option = new com.aliyun.dingtalkstorage_1_0.models.GetFileDownloadInfoRequest.GetFileDownloadInfoRequestOption()
                .setVersion(1L)
                .setPreferIntranet(false);
        com.aliyun.dingtalkstorage_1_0.models.GetFileDownloadInfoRequest getFileDownloadInfoRequest = new com.aliyun.dingtalkstorage_1_0.models.GetFileDownloadInfoRequest()
                .setUnionId("chyxxxxx")
                .setOption(option);
        try {
            client.getFileDownloadInfoWithOptions("854xxxx", "798xxxxx", getFileDownloadInfoRequest, getFileDownloadInfoHeaders, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
            }

        }        
    }
}
```

Python

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import sys

from typing import List

from alibabacloud_dingtalk.storage_1_0.client import Client as dingtalkstorage_1_0Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dingtalk.storage_1_0 import models as dingtalkstorage__1__0_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> dingtalkstorage_1_0Client:
        """
        Token を使用してアカウント Client を初期化
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        config.protocol = 'https'
        config.region_id = 'central'
        return dingtalkstorage_1_0Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        get_file_download_info_headers = dingtalkstorage__1__0_models.GetFileDownloadInfoHeaders()
        get_file_download_info_headers.x_acs_dingtalk_access_token = '<your access token>'
        option = dingtalkstorage__1__0_models.GetFileDownloadInfoRequestOption(
            version=1,
            prefer_intranet=False
        )
        get_file_download_info_request = dingtalkstorage__1__0_models.GetFileDownloadInfoRequest(
            union_id='chyxxxxx',
            option=option
        )
        try:
            client.get_file_download_info_with_options('854xxxx', '798xxxxx', get_file_download_info_request, get_file_download_info_headers, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
                pass

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        get_file_download_info_headers = dingtalkstorage__1__0_models.GetFileDownloadInfoHeaders()
        get_file_download_info_headers.x_acs_dingtalk_access_token = '<your access token>'
        option = dingtalkstorage__1__0_models.GetFileDownloadInfoRequestOption(
            version=1,
            prefer_intranet=False
        )
        get_file_download_info_request = dingtalkstorage__1__0_models.GetFileDownloadInfoRequest(
            union_id='chyxxxxx',
            option=option
        )
        try:
            await client.get_file_download_info_with_options_async('854xxxx', '798xxxxx', get_file_download_info_request, get_file_download_info_headers, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
                pass

if __name__ == '__main__':
    Sample.main(sys.argv[1:])
```

PHP

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
<?php

// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Dingtalk\Vstorage_1_0\Dingtalk;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dingtalk\Vstorage_1_0\Models\GetFileDownloadInfoHeaders;
use AlibabaCloud\SDK\Dingtalk\Vstorage_1_0\Models\GetFileDownloadInfoRequest\option;
use AlibabaCloud\SDK\Dingtalk\Vstorage_1_0\Models\GetFileDownloadInfoRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Sample {

    /**
     * Token を使用してアカウント Client を初期化
     * @return Dingtalk Client
     */
    public static function createClient(){
        $config = new Config([]);
        $config->protocol = "https";
        $config->regionId = "central";
        return new Dingtalk($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $client = self::createClient();
        $getFileDownloadInfoHeaders = new GetFileDownloadInfoHeaders([]);
        $getFileDownloadInfoHeaders->xAcsDingtalkAccessToken = "<your access token>";
        $option = new option([
            "version" => 1,
            "preferIntranet" => false
        ]);
        $getFileDownloadInfoRequest = new GetFileDownloadInfoRequest([
            "unionId" => "chyxxxxx",
            "option" => $option
        ]);
        try {
            $client->getFileDownloadInfoWithOptions("854xxxx", "798xxxxx", $getFileDownloadInfoRequest, $getFileDownloadInfoHeaders, new RuntimeOptions([]));
        }
        catch (Exception $err) {
            if (!($err instanceof TeaError)) {
                $err = new TeaError([], $err->getMessage(), $err->getCode(), $err);
            }
            if (!Utils::empty_($err->code) && !Utils::empty_($err->message)) {
                // err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
            }
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));
```

Go

```go theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.
package main

import (
  "os"
  util  "github.com/alibabacloud-go/tea-utils/v2/service"
  dingtalkstorage_1_0  "github.com/alibabacloud-go/dingtalk/storage_1_0"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  "github.com/alibabacloud-go/tea/tea"
)

/**
 * Token を使用してアカウント Client を初期化
 * @return Client
 * @throws Exception
 */
func CreateClient () (_result *dingtalkstorage_1_0.Client, _err error) {
  config := &openapi.Config{}
  config.Protocol = tea.String("https")
  config.RegionId = tea.String("central")
  _result = &dingtalkstorage_1_0.Client{}
  _result, _err = dingtalkstorage_1_0.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  client, _err := CreateClient()
  if _err != nil {
    return _err
  }

  getFileDownloadInfoHeaders := &dingtalkstorage_1_0.GetFileDownloadInfoHeaders{}
  getFileDownloadInfoHeaders.XAcsDingtalkAccessToken = tea.String("<your access token>")
  option := &dingtalkstorage_1_0.GetFileDownloadInfoRequestOption{
    Version: tea.Int64(1),
    PreferIntranet: tea.Bool(false),
  }
  getFileDownloadInfoRequest := &dingtalkstorage_1_0.GetFileDownloadInfoRequest{
    UnionId: tea.String("chyxxxxx"),
    Option: option,
  }
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    _, _err = client.GetFileDownloadInfoWithOptions(tea.String("854xxxx"), tea.String("798xxxxx"), getFileDownloadInfoRequest, getFileDownloadInfoHeaders, &util.RuntimeOptions{})
    if _err != nil {
      return _err
    }

    return nil
  }()

  if tryErr != nil {
    var err = &tea.SDKError{}
    if _t, ok := tryErr.(*tea.SDKError); ok {
      err = _t
    } else {
      err.Message = tea.String(tryErr.Error())
    }
    if !tea.BoolValue(util.Empty(err.Code)) && !tea.BoolValue(util.Empty(err.Message)) {
      // err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
    }

  }
  return _err
}

func main() {
  err := _main(tea.StringSlice(os.Args[1:]))
  if err != nil {
    panic(err)
  }
}
```

Node.js

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it
import Util, * as $Util from '@alicloud/tea-util';
import dingtalkstorage_1_0, * as $dingtalkstorage_1_0 from '@alicloud/dingtalk/storage_1_0';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import * as $tea from '@alicloud/tea-typescript';

export default class Client {

  /**
   * Token を使用してアカウント Client を初期化
   * @return Client
   * @throws Exception
   */
  static createClient(): dingtalkstorage_1_0 {
    let config = new $OpenApi.Config({ });
    config.protocol = "https";
    config.regionId = "central";
    return new dingtalkstorage_1_0(config);
  }

  static async main(args: string[]): Promise<void> {
    let client = Client.createClient();
    let getFileDownloadInfoHeaders = new $dingtalkstorage_1_0.GetFileDownloadInfoHeaders({ });
    getFileDownloadInfoHeaders.xAcsDingtalkAccessToken = "<your access token>";
    let option = new $dingtalkstorage_1_0.GetFileDownloadInfoRequestOption({
      version: 1,
      preferIntranet: false,
    });
    let getFileDownloadInfoRequest = new $dingtalkstorage_1_0.GetFileDownloadInfoRequest({
      unionId: "chyxxxxx",
      option: option,
    });
    try {
      await client.getFileDownloadInfoWithOptions("854xxxx", "798xxxxx", getFileDownloadInfoRequest, getFileDownloadInfoHeaders, new $Util.RuntimeOptions({ }));
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        // err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
      }

    }    
  }

}

Client.main(process.argv.slice(2));
```

C#

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {

        /**
         * Token を使用してアカウント Client を初期化
         * @return Client
         * @throws Exception
         */
        public static AlibabaCloud.SDK.Dingtalkstorage_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkstorage_1_0.Client(config);
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.SDK.Dingtalkstorage_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkstorage_1_0.Models.GetFileDownloadInfoHeaders getFileDownloadInfoHeaders = new AlibabaCloud.SDK.Dingtalkstorage_1_0.Models.GetFileDownloadInfoHeaders();
            getFileDownloadInfoHeaders.XAcsDingtalkAccessToken = "<your access token>";
            AlibabaCloud.SDK.Dingtalkstorage_1_0.Models.GetFileDownloadInfoRequest.GetFileDownloadInfoRequestOption option = new AlibabaCloud.SDK.Dingtalkstorage_1_0.Models.GetFileDownloadInfoRequest.GetFileDownloadInfoRequestOption
            {
                Version = 1,
                PreferIntranet = false,
            };
            AlibabaCloud.SDK.Dingtalkstorage_1_0.Models.GetFileDownloadInfoRequest getFileDownloadInfoRequest = new AlibabaCloud.SDK.Dingtalkstorage_1_0.Models.GetFileDownloadInfoRequest
            {
                UnionId = "chyxxxxx",
                Option = option,
            };
            try
            {
                client.GetFileDownloadInfoWithOptions("854xxxx", "798xxxxx", getFileDownloadInfoRequest, getFileDownloadInfoHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
                }
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err には code と message 属性が含まれており、開発者が問題を特定するのに役立ちます
                }
            }
        }

    }
}
```

## レスポンス

### レスポンスボディ

| 名前                   | タイプ                   | 説明                                                                                                           |
| -------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------ |
| protocol             | String                | ファイルダウンロードプロトコルです。   - **HEADER\_SIGNATURE**：Header リクエスト署名                                                  |
| headerSignatureInfo  | Object                | Header リクエスト署名情報です。  **説明**  protocol フィールドの値が HEADER\_SIGNATURE の場合に、このフィールドが有効になります。                       |
| resourceUrls         | Array of String       | 複数のダウンロード URL です。前にあるほど優先度が高くなります。                                                                           |
| headers              | `Map<String, String>` | リクエストヘッダー情報です。                                                                                               |
| expirationSeconds    | Integer               | 有効期限（単位：秒）です。                                                                                                |
| region               | String                | リージョンです。   - **ZHANGJIAKOU**：張家口 - **SHENZHEN**：深圳 - **SHANGHAI**：上海 - **SINGAPORE**：シンガポール - **UNKNOWN**：不明 |
| internalResourceUrls | Array of String       | イントラネット URL です。  **説明**  本フィールドは現在使用場面がありませんので、無視してください。                                                     |

### レスポンスボディの例

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
HTTP/1.1 200 OK
Content-Type:application/json

{
  "protocol" : "HEADER_SIGNATURE",
  "headerSignatureInfo" : {
    "resourceUrls" : [ "resource_url" ],
    "headers" : {
      "key" : "header_value"
    },
    "expirationSeconds" : 900,
    "region" : "ZHANGJIAKOU",
    "internalResourceUrls" : [ "internal_resource_url" ]
  }
}
```

### エラーコード

API 呼び出しでエラーが発生した場合は、エラーメッセージをもとに [グローバルエラーコード](/ja/open/development/server-api-error-codes-1) ドキュメントで解決策を検索してください。

| HttpCode | エラーコード                           | エラーメッセージ                        | 説明                                             |
| -------- | -------------------------------- | ------------------------------- | ---------------------------------------------- |
| 403      | orgAuthLevelNotEnough            | auth level of org is not enough | 企業認証レベルが低すぎます                                  |
| 403      | permissionDenied                 | %s                              | ユーザーにファイルダウンロード権限がありません                        |
| 400      | paramError                       | %s                              | パラメータエラー                                       |
| 400      | paramError.spaceId               | %s                              | パラメータエラー - spaceId                             |
| 400      | paramError.dentryId              | %s                              | パラメータエラー - dentryId                            |
| 400      | operationNotSupported            | %s                              | ファイルはダウンロードに対応していません                           |
| 400      | dentryDownloadProtocolNotSupport | %s                              | ダウンロードプロトコルがサポートされていません                        |
| 400      | fileArchived                     | %s                              | ファイルがアーカイブ状態のため、自動的にアーカイブ解除が実行されます。後で再試行してください |
| 404      | spaceNotExist                    | %s                              | スペースが存在しません                                    |
| 404      | dentryNotExist                   | %s                              | ファイルが存在しません                                    |
| 500      | systemError                      | %s                              | システムエラー                                        |
| 500      | unknownError                     | Unknown Error                   | 不明なエラー                                         |
| 503      | operationTimeout                 | %s                              | リクエストタイムアウト                                    |
