采用vb.net编写,c#的可以自行转换使用
[C#] 纯文本查看 复制代码 ''' <summary>
''' 根据文件路径创建上传的字节集
''' </summary>
''' <param name="boundary">分割符</param>
''' <param name="stringDict">上传文件的附带参数字典</param>
''' <param name="filePath">上传文件路径</param>
''' <param name="fileName">文件头数据体中filename的value值</param>
''' <returns>返回http POST上POSTDAT的数组</returns>
Public Function CreatFileToPostBytes(boundary As String, stringDict As IDictionary(Of String, String), filePath As String, fileName As String, postEncoding As Encoding) As Byte()
'判断字典跟文件路径是否为空
If stringDict Is Nothing OrElse String.IsNullOrWhiteSpace(filePath) OrElse String.IsNullOrWhiteSpace(boundary) Then
Return Nothing
End If
' 边界符
Dim beginBoundary As Byte() = postEncoding.GetBytes("--" & boundary & vbCrLf)
' Key-Value数据
Dim stringKeyHeader As String = "Content-Disposition: form-data; name=""{0}""" & vbCrLf &
"Content-Length: {1}" & vbCrLf & vbCrLf &
"{2}" & vbCrLf
'& "--" & boundary & vbCrLf
'文件头数据体
Dim filePartHeader As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""" & vbCrLf &
"Content-Type: image/jpeg" & vbCrLf &
"Content-Length: {2}" & vbCrLf & vbCrLf
' 最后的结束符
Dim endBoundary = postEncoding.GetBytes(vbCrLf & "--" & boundary & "--" & vbCrLf)
'获取文件二进制数组
Dim fileStream As FileStream = New FileStream(filePath, FileMode.Open)
Dim fileByte(fileStream.Length - 1) As Byte
fileStream.Read(fileByte, 0, fileByte.Length)
fileStream.Dispose()
Dim fileHeader As String = String.Format(filePartHeader, "file", fileName, fileByte.Length)
Dim fileHeaderBytes As Byte() = postEncoding.GetBytes(fileHeader)
' 开始拼数据
Using memStream = New MemoryStream()
'组装开始分界线数据体 到内存流中
memStream.Write(beginBoundary, 0, beginBoundary.Length)
' 组装上传文件附加携带的参数 到内存流中
For Each formitembytes As Byte() In
From key As String In stringDict.Keys
Select formitem = String.Format(stringKeyHeader, key, postEncoding.GetBytes(stringDict(key)).Length, stringDict(key))
Select postEncoding.GetBytes(formitem)
memStream.Write(formitembytes, 0, formitembytes.Length)
'写入分界符
memStream.Write(beginBoundary, 0, beginBoundary.Length)
Next
' 组装文件头数据体到内存流中
memStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length)
' 组装文件数据体到内存流中
memStream.Write(fileByte, 0, fileByte.Length)
' 写入最后的结束边界符
memStream.Write(endBoundary, 0, endBoundary.Length)
Dim ResultBytes As Byte() = memStream.ToArray
Return ResultBytes
End Using
End Function
各个不同的网站可能上传的附件参数跟文件头数据里的type不一样,请自行修改试用。转完后是byte()数组,可以直接把postdatatype设置成byte属性,然后直接post就好了。
|