You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PowerShell从API响应中获取文件类型并正确保存文件

解决PowerShell下载文件时自动确定后缀的问题

要自动确定文件后缀,你可以通过获取API响应头中的信息来实现——优先提取服务器指定的文件名,再退而求其次根据Content-Type映射后缀。修改后的完整代码如下:

$tokenUrl = "/api/v1/gettoken"
$bodyData = @{
    "roles"= @("CONSUMER.ALLFUNCTIONS")
    "callingApplicationId"="IZGpLpXoN"
    "applicationKey"="XpwR3ayFVtRCbIZGpLpXoNYdBfDQLUVb"
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri $tokenUrl -Method Post -ContentType 'application/json' -Body $bodyData 

$token = $response[0].token

$getDocumentUrl = "/api/v1/documents/single/65a6296932aab9ed621a29e1?requestedBy=1361"
$header = @{"token"=$token}

# 改用Invoke-WebRequest获取完整响应(包含头信息)
$docResponse = Invoke-WebRequest -Uri $getDocumentUrl -Method Get -Headers $header

$saveBasePath = "C:\code\"
$fileName = $null

# 1. 优先从Content-Disposition头提取服务器指定的文件名
if ($docResponse.Headers['Content-Disposition']) {
    $contentDisposition = [System.Net.Mime.ContentDisposition]::new($docResponse.Headers['Content-Disposition'])
    $fileName = $contentDisposition.FileName

    # 如果文件名无后缀,结合Content-Type补充
    if (-not [System.IO.Path]::HasExtension($fileName)) {
        $contentType = $docResponse.Headers['Content-Type']
        $typeMap = @{
            'image/tiff' = '.tif'
            'application/pdf' = '.pdf'
            'image/jpeg' = '.jpg'
            'image/png' = '.png'
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' = '.docx'
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' = '.xlsx'
        }
        $extension = $typeMap[$contentType] ?? '.bin'
        $fileName += $extension
    }
}
# 2. 无Content-Disposition时,用文档ID+Content-Type生成文件名
else {
    $contentType = $docResponse.Headers['Content-Type']
    $typeMap = @{
        'image/tiff' = '.tif'
        'application/pdf' = '.pdf'
        'image/jpeg' = '.jpg'
        'image/png' = '.png'
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' = '.docx'
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' = '.xlsx'
    }
    $extension = $typeMap[$contentType] ?? '.bin'
    $fileName = "65a6296932aab9ed621a29e1$extension"
}

# 拼接完整路径并保存二进制文件
$fullSavePath = Join-Path -Path $saveBasePath -ChildPath $fileName
$docResponse.Content | Set-Content -Path $fullSavePath -Encoding Byte

关键逻辑说明

  • 用Invoke-WebRequest替代Invoke-RestMethod:前者会返回包含响应头的完整对象,方便获取Content-Disposition(服务器指定文件名)和Content-Type(文件类型)。
  • 优先使用服务器指定的文件名:Content-Disposition头通常会携带服务器希望的文件名(包含正确后缀),这是最可靠的方式。
  • Content-Type映射后缀:如果没有文件名信息,根据常见的Content-Type与文件后缀的对应关系自动补充,未知类型默认用.bin避免文件损坏。
  • 二进制保存:用Set-Content -Encoding Byte确保二进制文件(如图片、PDF)不会因为文本编码问题损坏。

内容的提问来源于stack exchange,提问作者Rohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 02:53:09