上传损坏但文件大小正确?

时间:2012-09-04 20:35:31

标签: .net powershell png

我正在使用Invoke-Restmethod尝试将png文件上传到rapidshare,服务器上的文件大小是正确的但如果我下载文件它甚至不是图像,这绝对是一个编码问题,但我不知道是什么我做错了?

$FreeUploadServer = Invoke-RestMethod -Uri "http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver"
$url = "http://rs$FreeUploadServer.rapidshare.com/cgi-bin/rsapi.cgi"
$fields = @{sub='upload';login='username';password='pass';filename='2he1re.png';filecontent=$(Get-Content C:\libs\test.png -Raw)}

Invoke-RestMethod -Uri $url -Body $fields -Method Post -ContentType "image/png"

我尝试了各种各样的东西,任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分:2)

使用-Raw参数读取文件内容仍然会返回string对象,这对于像PNG这样的二进制文件可能会有问题。我认为RapidShare API期待URL编码的表单发布数据。试试这个:

## !! It would be nice if this worked, but it does not - see update below !!
Add-Type -AssemblyName System.Web
$fields = @{sub='upload';login='username';password='pass';filename='2he1re.png';
            filecontent=Get-Content C:\libs\test.png -Enc Byte -Raw}

BTW我想你可能想放弃设置ContentType。内容类型应为application/x-www-form-urlencoded - 我认为。

我发现this post对HtmlEncode和UrlEncode之间的区别非常有用。

更新:当正文采用哈希表格式时,Invoke-RestMethod似乎是编码POST正文的URL。真好。但是它似乎不接受字节数组。它期望散列表中的每个值都是一个字符串或可表示为字符串,即它在每个值上调用ToString()。这使得正确编码二进制数据变得具有挑战性。我对PowerShell团队有疑问。

好的,找到了合理的解决方法。还记得我之前提到过,将Body作为字符串传递相当于传入哈希表吗?好吧,事实证明有一个重要的区别。 :-)传入字符串时,cmdlet不会对其进行Url编码。因此,如果我们传入一个字符串,我们可以绕过我认为是这个cmdlet的限制(不支持散列表中的byte []值)。试试这个:

Add-Type -AssemblyName System.Web
$png  = [Web.HttpUtility]::UrlEncode((Get-Content C:\libs\test.png -Enc Byte -Raw))
$body = "sub=upload&login=username&password=pass&filename=2he1re.png&filecontent=$png"
Invoke-RestMethod -Uri $url -Body $body -Method Post