File upload problems in Multipart/form-data. C#

Asked

Viewed 575 times

0

Hello, my problem is this, I have a simple web application running on apache on localhost.

Which has the following code:

<?php
if (isset($_FILES['arquivo']))
{
    move_uploaded_file($_FILES['arquivo']['tmp_name'], "uploadedfile.pdf");

}

?>



<HTML>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="arquivo" id="arquivo"/>
<input type="submit" value="click here to send"/>
</form>

</HTML>

I would like to know how to upload my desired file in c# using httpwebrequest.

I tried the following:

public string Upload(string filePath)
        {
            string formdataTemplate = "Content-Disposition: form-data;name=\"arquivo\" ;filename=\"{0}\";\r\nContent-Type: application/pdf\r\n\r\n";
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/xxxx/fileuploader.php");
            request.ServicePoint.Expect100Continue = false;
            request.Referer = "http://localhost/policlinica/fileuploader.php";
            request.KeepAlive = false;
            request.Method = "POST";
            request.CookieContainer = cookieContainer;
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem = string.Format(formdataTemplate, Path.GetFileName(filePath));
                    byte[] formbytes = Encoding.UTF8.GetBytes(formitem);
                    requestStream.Write(formbytes, 0, formbytes.Length);
                    byte[] buffer = new byte[1024 * 4];
                    int bytesLeft = 0;

                    while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        requestStream.Write(buffer, 0, bytesLeft);
                    }

                }
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    return responseString;
                }

            }
            catch (WebException ex)
            {
                return ex.ToString();
            }
        }

But without success.

Thank you.

  • Show us what you’ve done with C# using Webrequest.

1 answer

0

Really need to use HttpWebRequest? You can reduce all this code by making a request POST on the server with this code snippet using WebClient:

public string Upload(string filePath) {
    System.Net.WebClient Client = new System.Net.WebClient();
    Client.Headers.Add("Content-Type", "binary/octet-stream");
    byte[] result = Client.UploadFile("http://localhost/policlinica/fileuploader.php", "POST", filePath);
    string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
    return s;
}

And in your PHP:

<?php

$uploads_dir = './files';

if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
  • 1

    I really have to use Httpwebrequest, because I’ve assembled this just for a test, I’ll make a request on a remote server which I don’t have access to edit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.