Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I want to upload text & files from a desktop application in c# to a web server (running i php),

So I try this code :

In C# :

C#
string URL = "http://localhost/TestUploadFile.php";
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
WebRequest webRequest = WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

Stream postDataStream = new MemoryStream();

//adding form data
string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine + "Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";
byte[] formItemBytes = Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate, "value", "valueTest"));
postDataStream.Write(formItemBytes, 0, formItemBytes.Length);

//adding file data

string FilePath = @"C:\test\";

string[] files = Directory.GetFiles(FilePath);

for(int i = 0; i < files.Length; i++)
{
    FileInfo fileInfo = new FileInfo(files[i]);
    string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine + "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + Environment.NewLine + "Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine;
    byte[] fileHeaderBytes = Encoding.UTF8.GetBytes(string.Format(fileHeaderTemplate, "UploadFile", fileInfo.FullName));
    postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);

    FileStream fileStream = fileInfo.OpenRead();

    byte[] bufferFiles = new byte[1024];

    int bytesRead = 0;

    while ((bytesRead = fileStream.Read(bufferFiles, 0, bufferFiles.Length)) != 0)
    {
        postDataStream.Write(buffer, 0, bytesRead);
    }

    fileStream.Close();
}

byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");

postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

webRequest.ContentLength = postDataStream.Length;

Stream reqStream = webRequest.GetRequestStream();

postDataStream.Position = 0;

byte[] buffer = new byte[1024];

int bytesRead = 0;

while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)
{
    reqStream.Write(buffer, 0, bytesRead);
}

postDataStream.Close();
reqStream.Close();

StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());
string Result = sr.ReadToEnd();

MessageBox.Show(Result);


In my WebApplication (in php)

PHP
<?php

$uploaddir = 'upload/'; // Relative Upload Location of data file

if(isset($_FILES['file']['tmp_name'])) {
    if (is_uploaded_file($_FILES['file']['tmp_name'])) {

        $uploadfile = $uploaddir . basename($_FILES['file']['name']);
        echo 'File '. $_FILES['file']['name']. ' uploaded successfully';
        if ( move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile) ) {
        echo "File is valid, and was successfully moved ";
    }
    else {
        print_r($_FILES);
    }
}
else {
    echo "Upload Failed !!!";
}
}

if(isset($_POST['value'])) {
echo $_POST['value'];
}
else {
echo 'not value';
}


The MessageBox return "Failed" for upload files and the valueTest for form data (success for form data)

I think the problem is in the Content-Type: application/octet-stream !!! I want to upload all type of file (.txt, .pdf, .msg, ...)

I can't understand how to Content-Type work and I do not know the importance of boundary !!!

Can you help me please ?
Posted
Updated 7-Mar-21 14:21pm

1 solution

Hi,


Boundary in Content Type : Link[^] go through this link it will clear your confusion.

Upload multiple files :

Before going to the code, your client code can upload multiple file only when your server code supports that but in your PHP code it looks like it can only accept single file.

C#
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);
        rs.Close();

        WebResponse wresp = null;
        try {
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
            
        } catch(Exception ex) {
            
            if(wresp != null) {
                wresp.Close();
                wresp = null;
            }
        } finally {
            wr = null;
        }
    }


Now you can call this code again again to upload multiple file.

You can use 'application/octet-stream'
 
Share this answer
 
Comments
Member 10872485 18-Aug-14 2:06am    
Thank you Suvabrata Roy for your answer !
If I call this method, what can I put a paramName ?!
If I use application/octet-stream, I can upload all type of files ?! Or each type of file, there is a content type ???
Member 10872485 18-Aug-14 2:25am    
I found this solution in :

http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data !?

I want to upload multi-files in one request :)
Suvabrata Roy 18-Aug-14 2:32am    
Yes, I have copy it from there because your server code dos't support multiple file upload you need to modify that first then you can upload multiple files.

Member 10872485 18-Aug-14 7:08am    
I just write :
var_dump($_FILES);exit;
in my server code, but it doesn't work !

I think that I have a problem in content_type !?

If I use application/octet-stream, I can upload all type off files (.csv, pdf, msg, .txt ) ???

Excuse me, but it's urgent !

Thank you in advance .
Suvabrata Roy 18-Aug-14 9:32am    
Go through this link : http://stackoverflow.com/questions/12010993/file-upload-error-application-octet-stream

Excuse me : we are professionals so as on when we have spare time we will share our knowledge to help others.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900