【问题标题】:Saving Video Data To File From POST request InputStream in PowerShell在 PowerShell 中将视频数据从 POST 请求 InputStream 保存到文件
【发布时间】:2016-08-10 19:38:52
【问题描述】:

我很难弄清楚如何保存通过 PowerShell 中的 HttpListener 发送给我的视频数据。我有以下内容,我认为只是将其发送回请求者,但我无法将其保存到 MP4 文件中。

    $req = $request
    $body = $req.InputStream
    $reader = New-Object System.IO.StreamReader ($body, $req.ContentEncoding)
    $msg = $reader.ReadToEnd()
    $reader.Close()

    [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($msg)
    $res.ContentLength64 = $buffer.Length
    $res.StatusCode = 200
    $res.OutputStream.Write($buffer, 0, $buffer.Length)
    $res.Close()

感谢您的宝贵时间!

更新:

我已经能够用它来制作文件,尽管出于某种原因在示例中它们使用了 8192 大小的字节,但 PowerShell 说它太大了。有了这个,我得到零长度文件,没有我可以告诉的错误。

    $path = "c:\matthew3.mp4"
    $file = New-Object System.IO.FileStream $path,CreateNew

    [byte]$bytes = 255

    [int]$bytes_read = 0

    while ( $bytes_read = $request.InputStream.Read($bytes, 0, $bytes.length) > 0 ) 

    {

        $file.Write($bytes, 0, $bytes_read)

    }

其实我确实报错了:

Exception calling "GetBytes" with "1" argument(s): "Array cannot be null.
Parameter name: chars"
At line:45 char:1
+ $buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

Exception calling "Write" with "3" argument(s): "Value cannot be null.
Parameter name: buffer"
At line:47 char:1
+ $response.OutputStream.Write($buffer, 0, $buffer.Length)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

【问题讨论】:

  • 真的是UTF8编码吗?我希望它是原始的,所以应该使用[Text.Encoding]::Default。无论如何,问题是什么?
  • 我正在尝试将其保存到文件中,我更新了帖子。我得到一个零长度文件。据我所知,它没有抱怨任何事情。我正在使用 Chrome 工具 Postman 发送二进制文件。视频文件会以原始格式发布吗?
  • 根据 Postman API 的工作方式,它可能是原始的,因为它对二进制数据最有效。或者它可以是 JSON 字符串化的。但是,从您添加的错误消息来看,根本没有收到任何内容。尝试逐行调试代码。

标签: powershell post inputstream outputstream httplistener


【解决方案1】:

因此,我们公司的主要开发人员 Nick 为我指明了正确的方向。

主要是我需要为 FileStream 对象添加 Write 标志,并在 InputStream 上使用 CopyTo 方法,然后关闭它们:

        $file = New-Object System.IO.FileStream $path,CreateNew,Write

        $context.Request.InputStream.CopyTo($file)

        $file.Close()

        $context.Request.InputStream.Close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    相关资源
    最近更新 更多