如何通过 vb.net 中的 API 发布文本和多个文件

问题描述 投票:0回答:0

公共子执行PostRequest() Dim FormDataTemplate As String = "--{0}" & vbCrLf & "Content-Disposition: form-data; name=""{1}""" & vbCrLf & vbCrLf & "{2}" & vbCrLf Dim HeaderTemplate As String = "--{0}" & vbCrLf & "Content-Disposition: form-data; name=""{1}""; filename=""{2}""" & vbCrLf & "Content-类型:{3}" & vbCrLf & vbCrLf

    Dim Url As String = "http://192.168.0.34:8042/api/UploadFiles"
    Dim request As HttpWebRequest = CType(WebRequest.Create(Url), HttpWebRequest)
    request.Method = "POST"
    request.KeepAlive = True
    Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
    request.ContentType = "multipart/form-data; boundary=" & boundary

    Dim requestStream As Stream = request.GetRequestStream()
    
    Dim item As String = String.Format(FormDataTemplate, boundary, "ClientId", "{""ClientId"":""1024""}")
    Dim itemBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(item)
    requestStream.Write(itemBytes, 0, itemBytes.Length)

    Dim fOpen As New OpenFileDialog
    fOpen.Multiselect = True

    If fOpen.ShowDialog = System.Windows.Forms.DialogResult.OK Then
        For Each F As String In fOpen.FileNames
            Dim newlineBytes As Byte() = Encoding.UTF8.GetBytes(vbCrLf)
            requestStream.Write(newlineBytes, 0, newlineBytes.Length)                
            Dim header As String = String.Format(HeaderTemplate, boundary, "Files", F.ToString(), GetMimeType(F.ToString))
            Dim headerbytes As Byte() = Encoding.UTF8.GetBytes(header)
            requestStream.Write(headerbytes, 0, headerbytes.Length)

            Dim buffer As Byte() = File.ReadAllBytes(F)
            requestStream.Write(buffer, 0, buffer.Length)
        Next
    End If

    Dim endBytes As Byte() = System.Text.Encoding.UTF8.GetBytes("--" & boundary & "--")
    requestStream.Write(endBytes, 0, endBytes.Length)
    requestStream.Close()
    Dim Str As String = ""
    Using response As WebResponse = request.GetResponse()

        Using reader As StreamReader = New StreamReader(response.GetResponseStream())
            Str = reader.ReadToEnd()
        End Using
    End Using
End Sub

出现 System.IO.IOException 错误:流意外结束,内容可能已被另一个组件读取

vb.net webapi form-data
© www.soinside.com 2019 - 2024. All rights reserved.