0

我正在尝试使用以下代码上传文件,但是当我上传文件时会引发异常: Header section has more than 10240 bytes (也许它没有正确终止)

我尝试这样做但不起作用:WebRequest POST with the file and parameters

Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)

request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True

Using requestStream As IO.Stream = request.GetRequestStream()
    Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"

    For Each key As String In otherParameters.Keys

        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)

        Dim formItem As String
        Dim formItemBytes As Byte()

        If key = "file" Then
           formItemBytes = StreamFile(otherParameters(key))
        Else
            formItem = String.Format(formDataTemplate, key, newLine, otherParameters(key))
            formItemBytes = Encoding.UTF8.GetBytes(formItem)
        End If

        requestStream.Write(formItemBytes, 0, formItemBytes.Length)

    Next key

    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)

    Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
    Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
    Dim headerBytes As Byte() = Encoding.UTF8.GetBytes(header)
    requestStream.Write(headerBytes, 0, headerBytes.Length)

    Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)

        Dim buffer(4096) As Byte
        Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)

        Do While (bytesRead > 0)

            requestStream.Write(buffer, 0, bytesRead)
            bytesRead = fileStream.Read(buffer, 0, buffer.Length)

        Loop

    End Using

    Dim trailer As Byte() = Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
    requestStream.Write(trailer, 0, trailer.Length)

End Using

Dim response As Net.WebResponse = request.GetResponse()

编辑:

我尝试了两种选择但不起作用:

Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2} Content-Type: {3}{2}{2}" 

Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}" & newLine & "Content-Type: {3}{2}{2}" 
4

0 回答 0