PHP curl to .NET HttpRequest: Files uploading to s

2019-01-15 23:11发布

问题:

What I am trying to achieve is to upload single/multiple .csv files to the server with a token authentication (No username or password required in Network credentials) and receive a response as well. I have a PHP script written using curl libs (which I have very minimal knowledge of), this script is fulfilling the purpose, but I intend to convert it into c# (HttpRequest).

PHP script:

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);


    $ch = curl_init('http://demo.schooling.net/school/attendance');



$DirPath="/opt/lampp/htdocs/schooling/Files/";
 // Create a CURLFile object


$Files=array();

if ($dh = opendir($DirPath)) 
{
    while (($file = readdir($dh)) !== false) 
    {
        if ($file == '.' || $file == '..') 
        {
            continue;
        }
               $Files[]='@'.$DirPath.$file;
           }
    closedir($dh);
}
if(!empty(Files))
{
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_FAILONERROR,false);


    curl_setopt_custom_postfields($ch, array('Files[]'=>$Files,'token'=>'0fc0975128d45cac2cechjhj676t5ft76f'));


    // Execute the handle
    $execResult=curl_exec($ch);


    if($execResult=== false)
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    else
    {
        echo 'Operation completed without any errors';
        echo $execResult;
    }

}

function redirect($redirect,$redirect_2,$message) ///confirm box pop up
{
    echo "<script>javascript:
    var ask = confirm('".$message."');
    if(ask==true)
    {

    }
    else
    {
        window.location = '".$redirect_2."';    
    }
    </script>";
}

function curl_setopt_custom_postfields($ch, $postfields, $headers = null) {
    $algos = hash_algos();
    $hashAlgo = null;
    foreach ( array('sha1', 'md5') as $preferred ) {
        if ( in_array($preferred, $algos) ) {
            $hashAlgo = $preferred;
            break;
        }
    }
    if ( $hashAlgo === null ) { list($hashAlgo) = $algos; }
    $boundary =
        '----------------------------' .
        substr(hash($hashAlgo, 'cURL-php-multiple-value-same-key-support' . microtime()), 0, 12);

    $body = array();
    $crlf = "\r\n";
    $fields = array();
    foreach ( $postfields as $key => $value ) {
        if ( is_array($value) ) {
            foreach ( $value as $v ) {
                $fields[] = array($key, $v);
            }
        } else {
            $fields[] = array($key, $value);
        }
    }

        foreach ( $fields as $field ) {
        list($key, $value) = $field;
        if ( strpos($value, '@') === 0 ) {
            preg_match('/^@(.*?)$/', $value, $matches);
            list($dummy, $filename) = $matches;
            $body[] = '--' . $boundary;
            $body[] = 'Content-Disposition: form-data; name="' . $key . '"; filename="' . basename($filename) . '"';
            $body[] = 'Content-Type: application/octet-stream';
            $body[] = '';
            $body[] = file_get_contents($filename);
        } else {
            $body[] = '--' . $boundary;
            $body[] = 'Content-Disposition: form-data; name="' . $key . '"';
            $body[] = '';
            $body[] = $value;
        }
    }
    $body[] = '--' . $boundary . '--';
    $body[] = '';
    $contentType = 'multipart/form-data; boundary=' . $boundary;
    $content = join($crlf, $body);
    $contentLength = strlen($content);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Length: ' . $contentLength,
        'Expect: 100-continue',
        'Content-Type: ' . $contentType,
    ));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
}
?>

Upon reading it here: http://www.c-sharpcorner.com/article/using-webrequest-and-webresponse-classes/ and using Postman I came up with this equivalent request in c#:

var client = new RestClient("http://demo.schooling.net/school/attendance");
var request = new RestRequest(Method.POST);

request.AddHeader("postman-token", "0fc0975128d45cac2cechjhj676t5ft76f");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "

------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"token\"\r\n\r\nfe60313b0edfdfaf757f974481659688\r\n

------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"Files[0]\"; filename=\"democollege-1-1-17.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n

------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"Files[1]\"; filename=\"democollege-1-1-17.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n

------WebKitFormBoundary7MA4YWxkTrZu0gW--

", ParameterType.RequestBody);

IRestResponse response = client.Execute(request);

Is this the right way to send any .csv files to a url and get an ok response from the server using C#?

UPDATED: I tried using the WebClient method but it threw me the exception:

Too many automatic redirections were attempted. 

how do I fix this? and am I sending the token correctly? the way it is shown in the php script above?

[HttpPost]
        public void SendCSV()
        {
            WebClient myWebClient = new WebClient();
            var authHeader = "token=0fc0975128d45cac2cechjhj676t5ft76f";
            myWebClient.Headers.Add("Authorization", authHeader);
            string fileName = "E:\\Uploads\\demo-1-2-3.csv";
            string uriString = "http://demo.schooling.net/school/attendance";
            byte[] responseArray = myWebClient.UploadFile(uriString, fileName);
        }

Best Regards.