如何用PowerShell Invoke-WebRequest内存中转二进制文件至API
直接中转内存中图片字节数组到API的PowerShell实现
你无需对已获取的$jpgResponse.Content做额外转换,它本身就是图片的字节数组,可以直接作为Invoke-WebRequest的-Body参数传入,全程不需要写入本地文件。
完整代码示例
# 获取远程图片的字节数组 $jpgParams = @{ 'Uri' = 'https://i.sstatic.net/iEQ9h.jpg?s=256&g=1' 'Method' = 'GET' 'Headers' = @{ 'Cache-Control' = 'no-cache' } } [Net.ServicePointManager]::SecurityProtocol = 'tls12, tls11' $jpgResponse = Invoke-WebRequest @jpgParams # 直接将内存中的字节数组POST到目标API $postParams = @{ 'Uri' = 'https://antijerry.com/api/v1/profilepic?name=tom.jpg' 'Method' = 'POST' 'ContentType' = 'image/jpeg' } $postResponse = Invoke-WebRequest @postParams -Body $jpgResponse.Content
关键说明
$jpgResponse.Content是Invoke-WebRequest返回的原始字节数据,符合目标API要求的图片格式- 保持
ContentType = 'image/jpeg'的设置,确保API能正确识别请求体的内容类型 - 修正了POST参数中Uri的双反斜杠为单斜杠,避免Uri解析错误
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

