开发者

Uploaded attachment PNG is not shown correctly

I use the following powershell and REST-API to upload attachment

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
  }
}

The function UploadPng executed successfu开发者_StackOverflow中文版lly and I can also get the response which contains the uploaded PNG url and uuid

But when I opened response url in browser to check the uploaded PNG, I found the uploaded image was not shown as expected and not same as the original one.

Uploaded attachment PNG is not shown correctly

Uploaded attachment PNG is not shown correctly

So, what`s wrong with the function UploadPng?


I can reproduce the same issue when using the same Powershell script.

To solve this issue, you can use the powershell command: [IO.File]::ReadAllBytes("$PngFileName") to read the file and no need to convert it to base64. Then you can change the content type to 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
  }
}

Or you can use the -InFile to create the attachment.

Here is PowerShell example:

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
  }
}

Update:

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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜