Upload file to Mediafire with C#

2.6k Views Asked by At

I read a lot in Mediafire developers section ,but it's seems that they are not provided libraries for C# developers, so i tried to use their web services API's

The normal scenario to upload a file as following:

1- Request for session_token through this Link

https://www.mediafire.com/api/user/get_session_token.php?email={0}&password={1}&application_id={2}&signature={3}&token_version=2


This Step works fine and i get the session_token
After that you use session_token in post request to upload a file through this link

 http://www.mediafire.com/api/unversioned/upload/simple.php?uploadkey={0}&session_token={1}

Mediafire documentation describe Raw HTTP Request for upload :

POST http://www.mediafire.com/api/unversioned/upload/simple.php?uploadkey=5bb66g94blnnk&session_token=aa22f5a968f827daf69fd6b3515110c43e036bc5d2ed8b81657dd1bdfe4b4c3e3ea6757d1f47bc3d6a001a16bc6f25abb486c5e779328a5769bd9ed6064edb69 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
X-Filehash:564dc5e9541a494e966066da8b2392e2e70e2438e4fcf4b0058cd9249abc4e1d
X-Filesize:29278
X-Filetype:text/plain
Content-Type: multipart/form-data; boundary=---------------------------41184676334
Content-Length: 29278

-----------------------------41184676334


Summer vacation
-----------------------------41184676334
Content-Disposition: form-data; name="image1"; filename="GrandCanyon.jpg"
Content-Type: image/jpeg

(Binary data not shown)
-----------------------------41184676334--

I tried to do HttpWebRequest but it's not work

    byte[] postData = File.ReadAllBytes(@"img2.jpg");

    System.Net.ServicePointManager.Expect100Continue = false;
    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create("http://www.mediafire.com/api/1.1/upload/upload.php?uploadkey=3kh445&session_token=" + respon.session_token);
    request.Method = "POST";
    request.Headers.Clear();
    request.UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0";
    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

    request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us,en;q=0.5");
    request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
    request.ContentType = "multipart/form-data";
    request.ContentLength = postData.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(postData, 0, postData.Length);
    requestStream.Flush();
    requestStream.Close();

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();


This code throw exception :

The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF


And I tried this code too and its keep request with no response :

string path = String.Format("http://www.mediafire.com/api/unversioned/upload/simple.php?uploadkey=3kh5656&session_token={0}", respon.session_token);

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string http = string.Format(
                        @"
POST {0} HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
X-Filehash:{1}
X-Filesize:{2}
X-Filetype:text/plain
Content-Type: multipart/form-data; boundary=---------------------------{6}
Content-Length: {3}

-----------------------------{6}


Summer vacation
-----------------------------{6}
Content-Disposition: form-data; name=""image1""; filename=""{4}""
Content-Type: image/jpeg

{5}
-----------------------------{6}--"
                        ,
                        path, 
                        GetFileHash(@"img2.jpg"), 
                        file.Length,
                        file.LongLength, 
                        filename, 
                        Encoding.Default.GetString(file),
                        DateTime.Now.Ticks.ToString("x")
                        );

            sock.Connect(new IPAddress(Dns.GetHostEntry("www.mediafire.com").AddressList[0].GetAddressBytes()), 80);
            sock.Send(Encoding.Default.GetBytes(http));

            while (sock.Available == 0)
                Thread.Sleep(1);


            file = new byte[sock.Available];
            sock.Receive(file, 0, sock.Available, SocketFlags.None);
            string result = Encoding.ASCII.GetString(file);
            sock.Close();

Sorry for bad English anything not clear please let me know i'll edit the question.

2

There are 2 best solutions below

0
On

MediaFire has recently released a C# SDK available on Github here:

https://github.com/MediaFire/mediafire-csharp-open-sdk

Within Visual Studio, you may also install it with NuGet by the following at the package manager console by typing:

Install-Package MediaFireSDK

In the GitHub readme file, you will find examples of how to upload a file.

0
On

Ahmed,

I do see a couple things wrong. It looks like MediaFire's documentation needs some more updating also though.

In your first example the url you use is http://www.mediafire.com/api/1.1/upload/upload.php?uploadkey=3kh445&session_token= . I'd like to point out a few things:

  1. That upload/upload.php is deprecated in the legacy version of the API so you can't use that API in v1.1. You would need to use upload/simple.php, upload/patch.php, upload/instant.php, upload/resumable.php or upload/update.php.
  2. 'Uploadkey' is not a parameter of any upload API. That is a response of the upload APIs to be used with poll_upload.php.

I see that the MediaFire documentation is wrong there and has gotten you confused. So, your URL should then look something closer to this: http://www.mediafire.com/api/1.1/upload/simple.php?session_token=

Another thing to note is that only the file's binary data should be in the post body. Even though the request type is POST, for MediaFire upload APIs, any other parameter will be in the URL query string (unless the parameter is under Header Data). So, session_token, signature, filedrop_key, path, action_on_duplicate and mtime will always be in the query string portion of the URL.

I see that in your XMLHTTPRequest example that you added the Content-Type=multipart/form-data header as you should, but the boundary information is missing from it. The second example you posted that didn't return a response has a properly formed Content-Type + boundary but it looks like you put the rest of the parameters into the POST body rather than the URL query string.

That last example also looks to have a malformed URL. If you are calling the legacy version of the MediaFire API you simply use www.mediafire.com/api/api category/api name.php, such as www.mediafire.com/api/upload/simple.php. If you need to call a versioned API you need to add the version to the URL www.mediafire.com/api/version number/api category/api name.php, such as www.mediafire.com/api/1.1/upload/simple.php.