Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

C# Mono HTTP multipart post to file hosting

  • 04-10-2009 3:25pm
    #1
    Registered Users, Registered Users 2 Posts: 2,719 ✭✭✭


    I'm trying to write a tool for uploading files to a file hosting site (ifile.it) but I am f*cked if I can get it to work, it is written in C# using Mono.

    The problem with my code is that it seems to abort the upload and the upload server returns "temp file can not be deleted" error. I have contacted the site administrators and they were good enough to go through the log files for the upload server I was trying to upload to, this is how I found out that my code was aborting the upload before it had finished.

    Any help would be greatly appreciated or if you happen to know of something like curl for Mono that would be good too (I have had look at the project on sourceforge and it is out of date :( )

    All the code is below:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Text;
    
    namespace mmp7
    {
        class MainClass
        {
            public static void Main(string[] args)
            {        
                string FilePath = "/home/cccp/test.jpg";
                
                IfileUpload iload = new IfileUpload();
                
                Console.WriteLine("result: " + iload.UploadtoIfile(FilePath));
            }
                
    
        }
        
        class IfileUpload
        {
            public string UploadtoIfile(string FilePath)
            {
                FileSystemInfo _file = new FileInfo(FilePath);
                DateTime dateTime2 = DateTime.Now;
                long l2 = dateTime2.Ticks;
                string s1 = "----------------------" + l2.ToString("x");
                HttpWebRequest httpWebRequest = GetWebrequest(s1);
                
                using (FileStream fileStream = new FileStream(_file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] bArr1 = Encoding.ASCII.GetBytes("\r\n--" + s1 + "\r\n");
                    
                    string s2 = GetRequestMessage(s1, _file.Name);
                    
                    byte[] bArr2 = Encoding.UTF8.GetBytes(s2);
                    Stream memStream = new MemoryStream();
                    memStream.Write(bArr1, 0, bArr1.Length);
                    memStream.Write(bArr2, 0, bArr2.Length);
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        memStream.Write(buffer, 0, bytesRead);
    
                    }
                    httpWebRequest.ContentLength = memStream.Length;
                    fileStream.Close();
    
                    Stream requestStream = httpWebRequest.GetRequestStream();
    
                    memStream.Position = 0;
                    byte[] tempBuffer = new byte[memStream.Length];
                    
                    //Console.WriteLine("Length: " + tempBuffer.Length);
                    
                    memStream.Read(tempBuffer, 0, tempBuffer.Length);
                    memStream.Close();
                    
                    
                    
                    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                    requestStream.Close();
    
                }
                
                string tm = "";
                using (Stream stream = httpWebRequest.GetResponse().GetResponseStream())
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    tm = streamReader.ReadToEnd();
    
                }
                return tm;
            }
                
            private string GetRequestMessage(string boundary, string FName)
            {
    
                StringBuilder stringBuilder = new StringBuilder();
                
                stringBuilder.Append(boundary);
                stringBuilder.Append("\r\n");
                
                stringBuilder.Append("Content-Disposition: form-data; name=\"");
                stringBuilder.Append("filecontent");
                stringBuilder.Append("\"; filename=\"");
                stringBuilder.Append(FName);
                stringBuilder.Append("\"");
                stringBuilder.Append("\r\n");
                
                stringBuilder.Append("Content-Type: ");
                stringBuilder.Append("multipart/form-data");
                stringBuilder.Append("\r\n");
                
                   //stringBuilder.Append("Content-Transfer-Encoding: ");
                   //stringBuilder.Append("binary");
                
                //stringBuilder.Append("\r\n");
                //stringBuilder.Append(boundary);
                
                //stringBuilder.Append("\r\n");
                stringBuilder.Append("\r\n");
                
                 Console.WriteLine("START:");
                Console.WriteLine(stringBuilder.ToString());
                Console.WriteLine("END.");
                
                return stringBuilder.ToString();
            }
                
            private CookieContainer _cockies = new CookieContainer();
                
            private HttpWebRequest GetWebrequest(string boundary)
            {                
                Uri uri = new Uri("http://s26.ifile.it/upload?");
                
                   HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                
                httpWebRequest.CookieContainer = _cockies;
                
                httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                
                httpWebRequest.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.14) Gecko/2009090216 Ubuntu/9.04 (jaunty) Firefox/3.0.14";
                
                httpWebRequest.Referer = "http://ifile.it/upload:classic";
                
                httpWebRequest.Method = "POST";
                httpWebRequest.KeepAlive = true;
                httpWebRequest.Timeout = -1;
    
                httpWebRequest.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    
                httpWebRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
                
                httpWebRequest.Headers.Add("Accept-Language", "en-us,en;q=0.5");
    
                return httpWebRequest;
            }
        }
        
    }
    

    Thanks for any and all help.


Comments

  • Closed Accounts Posts: 1,567 ✭✭✭Martyr


    Here is what the site code uses when uploading:
    POST /upload?apikey= HTTP/1.1
    Accept: text/*
    Content-Type: multipart/form-data; boundary=----------cH2Ef1cH2Ef1Ij5ei4ae0Ij5GI3ae0
    User-Agent: Shockwave Flash
    Host: s30.ifile.it
    Content-Length: 27538
    Connection: Keep-Alive
    Cache-Control: no-cache
    Cookie: ifileit_sess=ac2046157c6a60d6a84042a841cbe1ac31903539; __utma=256377427.27208703.1254731852.1254731852.1254731852.1; __utmb=256377427.1.10.1254731852; __utmc=256377427; __utmz=256377427.1254731852.1.1.utmcsr=s26.ifile.it|utmccn=(referral)|utmcmd=referral|utmcct=/
    
    ------------cH2Ef1cH2Ef1Ij5ei4ae0Ij5GI3ae0
    Content-Disposition: form-data; name="Filename"
    
    kermit.jpg
    ------------cH2Ef1cH2Ef1Ij5ei4ae0Ij5GI3ae0
    Content-Disposition: form-data; name="Filedata"; filename="kermit.jpg"
    Content-Type: application/octet-stream
    
    <JPEG binary data removed>
    ------------cH2Ef1cH2Ef1Ij5ei4ae0Ij5GI3ae0
    Content-Disposition: form-data; name="Upload"
    
    Submit Query
    ------------cH2Ef1cH2Ef1Ij5ei4ae0Ij5GI3ae0--HTTP/1.1 200 OK
    Server: Microsoft IIS/7.0
    Date: Mon, 05 Oct 2009 08:38:14 GMT
    Content-Type: application/json; charset=utf-8
    Transfer-Encoding: chunked
    Connection: keep-alive
    Expires: Mon, 26 Jul 1997 05:00:00 GMT
    Last-Modified: Mon, 05 Oct 2009 08:38:14 GMT
    Cache-Control: post-check=0, pre-check=0
    Pragma: no-cache
    
    f2
    {"status":"ok","url":"http:\/\/ifile.it\/lr5bp37\/kermit.jpg","file_key":"lr5bp37","file_size":"27120","file_md5":"a8705eaee3a925a61cd0cb9997d206f6","file_mime":"image\/jpeg","file_name":"kermit.jpg","hash":"cf1461634b6e36d9fdbeec483dd1ea10"}
    0
    

    and here is what your code sends for same file
    POST /upload? HTTP/1.1
    Content-Type: multipart/form-data; boundary=----------------------8cc13b70ea19c14
    User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.14) Gecko/2009090216 Ubuntu/9.04 (jaunty) Firefox/3.0.14
    Referer: http://ifile.it/upload:classic
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Accept-Encoding: gzip,deflate
    Accept-Language: en-us,en;q=0.5
    Host: s26.ifile.it
    Content-Length: 27314
    Expect: 100-continue
    Connection: Keep-Alive
    
    
    ------------------------8cc13b70ea19c14
    ----------------------8cc13b70ea19c14
    Content-Disposition: form-data; name="filecontent"; filename="kermit.jpg"
    Content-Type: multipart/form-data
    

    <jpeg binary removed>
    HTTP/1.1 200 OK
    Server: Microsoft IIS/7.0
    Date: Mon, 05 Oct 2009 08:40:55 GMT
    Content-Type: application/json; charset=utf-8
    Transfer-Encoding: chunked
    Connection: keep-alive
    Expires: Mon, 26 Jul 1997 05:00:00 GMT
    Last-Modified: Mon, 05 Oct 2009 08:40:54 GMT
    Cache-Control: post-check=0, pre-check=0
    Pragma: no-cache
    
    3d
    {"status":"error","message":"unable to delete tempfile [e5]"}
    0
    

    perhaps it's do with your headers/cookies?


  • Closed Accounts Posts: 1,567 ✭✭✭Martyr


    If you check RFC 1867 Form Based File Upload in HTML

    It gives example:
    Content-type: multipart/form-data, boundary=AaB03x

    --AaB03x
    content-disposition: form-data; name="field1"

    Joe Blow
    --AaB03x
    content-disposition: form-data; name="pics"
    Content-type: multipart/mixed, boundary=BbC04y

    In your code, you're using hyphens at the beginning which is acceptable, but could confuse anyone reading code or cause parse problem on server.

    rfc recommends you start with underscore..but anyway, that's where the problem is.

    if you add the following to end of stream after writing file data

    [php]string cd_end = "\r\n" + "--" + boundary + "\r\nContent-Disposition: form-data; name=\"Upload\"\r\n\r\nSubmit Query\r\n--" + boundary + "--";[/php]

    also in the GetRequestMessage method:

    [PHP] private string GetRequestMessage(string boundary, string FName)
    {
    StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.Append("--" + boundary + "\r\n");
    stringBuilder.Append("Content-Disposition: form-data; name=\"Filename\"\r\n\r\n");
    stringBuilder.Append(FName + "\r\n--" + boundary + "\r\n");
    stringBuilder.Append("Content-Disposition: form-data; name=\"Filedata\"; filename=\"" + FName + "\"\r\n");
    stringBuilder.Append("Content-Type: application/octet-stream\r\n\r\n");

    System.Net.ServicePointManager.Expect100Continue = false;
    return stringBuilder.ToString();
    }[/PHP]

    this should then work fine..
    POST /upload?apikey= HTTP/1.1
    Content-Type: multipart/form-data; boundary=633903579164531250
    User-Agent: IFile Uploader
    Cache-Control: no-cache
    Host: s30.ifile.it
    Content-Length: 27462
    Connection: Keep-Alive

    --633903579164531250
    Content-Disposition: form-data; name="Filename"

    kermit.jpg
    --633903579164531250
    Content-Disposition: form-data; name="Filedata"; filename="kermit.jpg"
    Content-Type: application/octet-stream

    <jpeg data>
    --633903579164531250
    Content-Disposition: form-data; name="Upload"
    
    Submit Query
    --633903579164531250--
    

    and the response from server..
    HTTP/1.1 200 OK
    Server: Microsoft IIS/7.0
    Date: Mon, 05 Oct 2009 15:45:21 GMT
    Content-Type: application/json; charset=utf-8
    Transfer-Encoding: chunked
    Connection: keep-alive
    Expires: Mon, 26 Jul 1997 05:00:00 GMT
    Last-Modified: Mon, 05 Oct 2009 15:45:21 GMT
    Cache-Control: post-check=0, pre-check=0
    Pragma: no-cache
    
    100
    {"status":"ok","url":"http:\/\/ifile.it\/2ln5amr\/kermit.jpg","file_key":"2ln5amr","file_size":"27120","file_md5":"a8705eaee3a925a61cd0cb9997d206f6","file_mime":"image\/jpeg","file_name":"kermit.jpg","hash":"1582e68cd75a454fc0d7ce86d64de607"}
    0
    


  • Registered Users, Registered Users 2 Posts: 2,719 ✭✭✭ARGINITE


    Thanks man, I have been banging my head against a wall with this code for a while now. It's amazing how much you forget when your teaching kids ever day rather than coding :D

    Will give it a go this evening.

    Works, thank you!


  • Registered Users, Registered Users 2 Posts: 7,468 ✭✭✭Evil Phil


    ARGINITE wrote: »
    Works, thank you!


    Then flag the thread as [Solved] please, thank you.


  • Registered Users, Registered Users 2 Posts: 2,719 ✭✭✭ARGINITE


    I would, but I couldn't find where to change it and then I went for dinner :D

    Where is the option to change it?


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 7,468 ✭✭✭Evil Phil


    Edit your original post, you'll need to use the 'Go Advanced' button and then select it from the dropdown.


  • Registered Users, Registered Users 2 Posts: 2,719 ✭✭✭ARGINITE


    I can't find the drop down menu :'(
    Honest!


  • Registered Users, Registered Users 2 Posts: 7,468 ✭✭✭Evil Phil


    Kinda weird, anyway I've done it for you now.


Advertisement