像ASP.NET中的PHP CURLFile之类的东西

时间:2016-12-03 08:56:25

标签: c# php asp.net vb.net

我是.NET新手,我想要CURLFile之类的东西,但是在C#或VB.NET中。 在PHP中我们使用:

$post_fields = array(
    'id' => $id,
    'document' => new CURLFile(realpath("ufile/data.txt")),
    'caption' => $caption
);
$url = 'https://www.example.com/gdata/';

function makeCurl($method, $datas)
{
    global $url;
    $ch = curl_init($url . $method);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $datas);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $server_output = curl_exec($ch);
    echo $server_output;
    curl_close($ch);
    return $server_output;
}
makeCurl("sendingFile", $post_fields);

如何使用C#或VB.NET中的其他参数发送文件内容?

更新: 根据@MrGadget评论: 我没有太多关于接收方的信息。我只有这方面的信息是期望" multipart / form-data"唯一的反应是" ok"或者"糟糕的请求"。使用上面的PHP代码,我们总能得到" ok"。现在我们调用WebRequest.Create来调用带有上面代码的php文件来发送文件。我只是尝试在.Net中进行操作并通过调用php。

1 个答案:

答案 0 :(得分:0)

我发现this ...没有经过测试或改进......看看你是否可以用它做点什么。

VB代码:

Imports System.Security.Cryptography
Imports System.Collections.Specialized
Imports System.IO

Public Shared Sub HttpUploadFile(url As String, file As String, paramName As String, contentType As String, nvc As NameValueCollection)
    Dim boundary As String = "---------------------------" + DateTime.Now.Ticks.ToString("x")
    Dim boundarybytes As Byte() = Text.Encoding.ASCII.GetBytes((Convert.ToString(vbCr & vbLf & "--") & boundary) + vbCr & vbLf)

    Dim wr As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
    wr.ContentType = Convert.ToString("multipart/form-data; boundary=") & boundary
    wr.Method = "POST"
    wr.KeepAlive = True
    wr.Credentials = Net.CredentialCache.DefaultCredentials

    Dim rs As Stream = wr.GetRequestStream()

    Dim formdataTemplate As String = "Content-Disposition: form-data; name=""{0}""" & vbCrLf & vbCrLf & "{1}"
    For Each key As String In nvc.Keys
        rs.Write(boundarybytes, 0, boundarybytes.Length)
        Dim formitem As String = String.Format(formdataTemplate, key, nvc(key))
        Dim formitembytes As Byte() = Text.Encoding.UTF8.GetBytes(formitem)
        rs.Write(formitembytes, 0, formitembytes.Length)
    Next
    rs.Write(boundarybytes, 0, boundarybytes.Length)

    Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""" & vbCrLf & "Content-Type: {2}" & vbCrLf & vbCrLf
    Dim header As String = String.Format(headerTemplate, paramName, file, contentType)
    Dim headerbytes As Byte() = Text.Encoding.UTF8.GetBytes(header)
    rs.Write(headerbytes, 0, headerbytes.Length)

    Dim fileStream As New FileStream(file, FileMode.Open, FileAccess.Read)
    Dim buffer As Byte() = New Byte(4095) {}
    Dim bytesRead As Integer = 0
    While (InlineAssignHelper(bytesRead, fileStream.Read(buffer, 0, buffer.Length))) <> 0
        rs.Write(buffer, 0, bytesRead)
    End While
    fileStream.Close()

    Dim trailer As Byte() = Text.Encoding.ASCII.GetBytes((Convert.ToString(vbCrLf & "--") & boundary) + "--" & vbCrLf)
    rs.Write(trailer, 0, trailer.Length)
    rs.Close()

    Dim wresp As WebResponse = Nothing
    Try
        wresp = wr.GetResponse()
        Dim stream2 As Stream = wresp.GetResponseStream()

        Dim reader2 As New StreamReader(stream2)
    Catch ex As Exception

        If wresp IsNot Nothing Then
            wresp.Close()
            wresp = Nothing
        End If
    Finally
        wr = Nothing
    End Try
End Sub

Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
End Function

原始C#代码:

public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) {
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
    wr.ContentType = "multipart/form-data; boundary=" + boundary;
    wr.Method = "POST";
    wr.KeepAlive = true;
    wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

    Stream rs = wr.GetRequestStream();

    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
    foreach (string key in nvc.Keys)
    {
        rs.Write(boundarybytes, 0, boundarybytes.Length);
        string formitem = string.Format(formdataTemplate, key, nvc[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        rs.Write(formitembytes, 0, formitembytes.Length);
    }
    rs.Write(boundarybytes, 0, boundarybytes.Length);

    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
    string header = string.Format(headerTemplate, paramName, file, contentType);
    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    rs.Write(headerbytes, 0, headerbytes.Length);

    FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) {
        rs.Write(buffer, 0, bytesRead);
    }
    fileStream.Close();

    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    rs.Write(trailer, 0, trailer.Length);
    rs.Close();

    WebResponse wresp = null;
    try {
        wresp = wr.GetResponse();
        Stream stream2 = wresp.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);

    } catch(Exception ex) {

        if(wresp != null) {
            wresp.Close();
            wresp = null;
        }
    } finally {
        wr = null;
    }
}