Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to upload file via c# post request? ownCloud

i`m using ownCloud (open source cloud) and i have a form to upload files the form sending the post request to upload.php file that handle the upload. the request have a lot of fields and need to send all info and cookie.

i need to develop a c# code to upload files to the cloud. the best way in my opinion is to make a request similar to the request that the form does. what do you think? any suggestions?

p.s i read the following solutions but it is not working. Sending Files using HTTP POST in c# http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code Upload files with HTTPWebrequest (multipart/form-data)

thanks

here is some of the code:

the form:

<form data-upload-id='1'
id="data-upload-form"
class="file_upload_form"
action="<?php print_unescaped(OCP\Util::linkTo('files', 'ajax/upload.php')); ?>"
method="post"
enctype="multipart/form-data"
target="file_upload_target_1">

<input type="hidden" name="MAX_FILE_SIZE" id="max_upload" value="<?php p($_['uploadMaxFilesize']) ?>">

<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" id="requesttoken">
<input type="hidden" class="max_human_file_size" value="(max <?php p($_['uploadMaxHumanFilesize']); ?>)">
 <input type="hidden" name="dir" value="<?php p($_['dir']) ?>" id="dir">
<input type="file" id="file_upload_start" name='files[]'/>
<a href="#" class="svg"></a>
                </form>

This the way the request seen to me:

enter code here

Request URL:http://my-url/owncloud/index.php/apps/files/ajax/upload.php
Request Method:POST
Status Code:200 OK
Request Headersview parsed
POST /owncloud/index.php/apps/files/ajax/upload.php HTTP/1.1
Host: my-url
Connection: keep-alive
Content-Length: 730
Accept: */*
requesttoken: 0bbcd458174e76e139ad
Origin: http://my-url
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Referer: http://my-url/owncloud/index.php/apps/files
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: oc_username=tal; oc_token=f24c041e992624d10cabbaa16aa6aeea; oc_remember_login=1; __utma=220528984.2016256779.1375771228.1375771228.1375862096.2; __utmz=220528984.1375771228.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); olfsk=olfsk4827894743066281; hblid=QHgh67nWTyXfpzWe6B1Tj9Z3JM0QBCfA; 510e8a1de6274=eqavm1nikkon6ush7con3o6ar6
Request Payload
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="MAX_FILE_SIZE"

537919488
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="requesttoken"

0bbcd458174e76e139ad
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="dir"

/
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="files[]"; filename="bg.png"
Content-Type: image/png


------WebKitFormBoundaryVhC3ZFEhWXiSUZYT--
Response Headersview parsed
HTTP/1.1 200 OK
Date: Sun, 08 Sep 2013 07:21:02 GMT
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7+squeeze16
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
X-Content-Type-Options: nosniff
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 132
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/plain; charset=utf-8

i tried this code

 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);   

                //StreamReader reader3 = new StreamReader(rs);
                rs.Close();




                WebResponse wresp = null;
                try 
                {
                    wresp = wr.GetResponse();
                    Stream stream2 = wresp.GetResponseStream();
                    StreamReader reader2 = new StreamReader(stream2);
                    MessageBox.Show((string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd())));
                    Debug.WriteLine(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));

                } 
                catch(Exception ex) 
                {
                    Debug.WriteLine("Error uploading file", ex);

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

the calling function:

NameValueCollection nvc = new NameValueCollection();
                nvc.Add("id", "TTR");
        nvc.Add("btn-submit-photo", "Upload");
        FilesClass.HttpUploadFile("http://192.168.49.108/owncloud/index.php/apps/files/ajax/upload.php", @"C:\t.txt", "files[]", "text/plain", nvc);

the response from the server is {"data":{"message":"Authentication error"},"status":"error"} that mean that i was rejected by upload.php maybe i need to send the cookie?

like image 289
user2153497 Avatar asked Oct 22 '22 01:10

user2153497


1 Answers

Instead of trying to simulate a POST upload (which ownCloud makes fairly difficult due to security issues) you can use WebDAV to upload the file.

Simply send a PUT request to http://example.com/owncloud/remote.php/webdav/some/path

like image 181
Icewind Avatar answered Oct 23 '22 18:10

Icewind