在vb.net中将文件作为FormData上载?

在vb.net中将文件作为FormData上载?,vb.net,Vb.net,在vb.net中将一些表单数据上载到API端点时遇到问题 来自供应商的示例: curl -X POST -H 'Authorization: Token token=sfg999666t673t7t82' -H 'Content-Type: multipart/form-data' -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' -F file=@/Users/

在vb.net中将一些表单数据上载到API端点时遇到问题

来自供应商的示例:

curl -X POST -H 'Authorization: Token token=sfg999666t673t7t82'
  -H 'Content-Type: multipart/form-data' -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' 
  -F file=@/Users/user1/Downloads/download.jpeg -F file_name=nameForFile 
  -F is_shared=true -F targetable_id=1 -F targetable_type=Lead -X POST "https://domain.freshsales.io/api/documents"
VB.NET代码

不知羞耻地从()

调用函数

这是我的电话:

Dim headers As NameValueCollection = New NameValueCollection()
headers.Add("Token", "token=youguessedit;")
Dim nvc As NameValueCollection = New NameValueCollection()
nvc.Add("is_shared", true)
nvc.Add("targetable_id", 1)
nvc.Add("targetable_type", "Lead")

HttpUploadFile("c:\test\file.pdf", "file", "application/pdf", nvc, headers);
我认为我的部分问题在于标题的附加方式:

  Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
在这种情况下,API端点需要file=和file_name=如何更正标头


有谁能指出我还出了什么问题吗?有更简单的方法吗?

这里有一个简单的控制台应用程序示例,使用
HttpClient
MultipartFormDataContent
来处理所有的头文件和流式传输文件,如果需要额外的头文件,这个示例也可以使用Postman Echo(此处仅显示
Token
)确保将它们添加到
HttpClient.DefaultRequestHeaders

Dim response As New HttpResponseMessage
Dim path As String = "C:\\Temp\\upload.pdf"
Dim uri As New Uri("https://postman-echo.com/post")

Using form As New MultipartFormDataContent,
    fs As New FileStream(path, FileMode.Open),
    content As New StreamContent(fs),
    httpClient As New HttpClient
    form.Add(content)
    httpClient.DefaultRequestHeaders.Add("Token", "Super Secret")
    response = httpClient.PostAsync(uri, form).GetAwaiter.GetResult()
    Console.WriteLine("Is Successfull: " & response.IsSuccessStatusCode)
End Using
编辑:使用语句清除嵌套的

Dim response As New HttpResponseMessage
Dim path As String = "C:\\Temp\\upload.pdf"
Dim uri As New Uri("https://postman-echo.com/post")

Using form As New MultipartFormDataContent,
    fs As New FileStream(path, FileMode.Open),
    content As New StreamContent(fs),
    httpClient As New HttpClient
    form.Add(content)
    httpClient.DefaultRequestHeaders.Add("Token", "Super Secret")
    response = httpClient.PostAsync(uri, form).GetAwaiter.GetResult()
    Console.WriteLine("Is Successfull: " & response.IsSuccessStatusCode)
End Using