Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c# - PHP curl to .NET HttpRequest: Files uploading to server

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 = "
";
    $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
Content-Disposition: form-data; name="token"

fe60313b0edfdfaf757f974481659688


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




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




------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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...