powershell 上传的附件PNG未正确显示

2guxujil  于 2022-12-23  发布在  Shell
关注(0)|答案(1)|浏览(165)

我使用下面的powershell和REST-API来上传附件

class TfsHelper{
#...
  [string]UploadPng([string]$TfsProject, [string]$PngFileName) {
    $uri = "http://$organization/$TfsProject/_apis/wit/attachments?fileName=image.png&api-version=5.1"
    $strPngBase64 = [convert]::ToBase64String((Get-Content $PngFileName -Encoding byte))  
    $rtn = Invoke-RestMethod -Uri $uri -Method POST -Headers $this.Header `
      -Body $strPngBase64 `
      -ContentType 'application/octet-stream'
    return $rtn.url
  }
}

函数UploadPng成功执行,我也可以得到包含上传的PNG url和uuid的响应
但是当我打开浏览器中的响应网址检查上传的PNG时,我发现上传的图像没有按预期显示,与原始图像不一样。
第一节第一节第一节第一节第一次
那么,UploadPng函数有什么问题呢?

ippsafx7

ippsafx71#

我可以在使用相同的Powershell脚本时重现相同的问题。
要解决此问题,可以使用powershell命令:[IO.File]::ReadAllBytes("$PngFileName")读取文件,无需将其转换为base64。然后,您可以将内容类型更改为application/json

class TfsHelper{
#...
  [string]UploadPng([string]$TfsProject, [string]$PngFileName) {
    $uri = "http://$organization/$TfsProject/_apis/wit/attachments?fileName=image.png&api-version=5.1"
    $file = [IO.File]::ReadAllBytes("$PngFileName") 
    $rtn = Invoke-RestMethod -Uri $uri -Method POST -Headers $this.Header `
      -Body $file  `
      -ContentType 'application/json'
    return $rtn.url
  }
}

或者您可以使用-InFile创建附件。
下面是PowerShell示例:

class TfsHelper{
#...
  [string]UploadPng([string]$TfsProject, [string]$PngFileName) {
    $uri = "http://$organization/$TfsProject/_apis/wit/attachments?fileName=image.png&api-version=5.1"
    $file = Get-ChildItem -Path "filepath" 
    $rtn = Invoke-RestMethod -Uri $uri -Method POST -Headers $this.Header `
      -InFile $file `
      -ContentType 'application/octet-stream'
    return $rtn.url
  }
}

更新日期:

class TfsHelper{
  [string]UploadPng([string]$TfsProject, [string]$PngFileName) {
    $uri = "https://dev.azure.com/orgname/$TfsProject/_apis/wit/attachments?fileName=image.png&api-version=5.1"
    $file = Get-ChildItem -Path "$PngFileName" 
    $token = "PAT"
    $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
    $rtn = Invoke-RestMethod -Uri $uri -Method POST -Headers @{Authorization = "Basic $token"} `
      -InFile $file `
      -ContentType 'application/octet-stream'

    return $rtn.url
  }
}

$uploadpng = [TfsHelper]::new()

echo $uploadpng.UploadPng("projectname","pngpath")

相关问题