简体   繁体   English

类似于ASP.NET中的PHP CURLFile

[英]Something like PHP CURLFile in ASP.NET

I am new to .NET and I want something like CURLFile but in C# or VB.NET. 我是.NET的新手,我想要CURLFile之类的东西,但是使用C#或VB.NET。 In PHP we use this : 在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);

How can I send file contents with other parameters like that in C# or VB.NET? 如何使用其他参数(如C#或VB.NET)发送文件内容?

UPDATE : According to the @MrGadget comment: I dont have much information about receiving side.Only information i have is that side expect "multipart/form-data" and the only response is "ok" or "bad request". 更新:根据@MrGadget的评论:我没有太多有关接收方的信息。我所拥有的唯一信息是该方希望“ multipart / form-data”,并且唯一的响应是“ ok”或“ bad request”。 With PHP code above we always get "ok". 使用上面的PHP代码,我们总能获得“ OK”。 for now we call WebRequest.Create to call a php file with above code to send file. 现在我们调用WebRequest.Create来调用带有上述代码的php文件来发送文件。 i just try to do it in .Net and pass calling php. 我只是尝试在.Net中做到这一点,并通过调用php。

I found this ...not tested or refined...see if you can make something with it. 我发现 ...未经测试或改进...看看是否可以用它做点什么。

VB Code: 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

Original C# code: 原始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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM