TRX
TRX

Reputation: 747

How to get multipart request data in aspx?

I am trying send HttpPost request from Android to C# (.net 3.5) aspx server. I am using Apache multipart entity builder builds entity at Android side:

entityBuilder.addTextBody("username", username);
entityBuilder.addTextBody("password", password);
entityBuilder.addBinaryBody("file", file);

And try to get data at C# server side:

protected void Page_Load(object sender, EventArgs e)
{
    string[] keys = Request.Form.AllKeys;  // only username and password keys received.

    for (int i = 0; i < keys.Length; i++)
    {
         string [] tmp = Request.Form.GetValues (keys[i]);
    }
}

I can get TextBody part keys and values in the Request (username and password). But no BinaryBody key or data received. I do not know why?

Upvotes: 0

Views: 909

Answers (2)

TRX
TRX

Reputation: 747

Solution:

HttpFileCollection MyFiles = Request.Files;
// ...
for (int l = 0; l < MyFiles.Count; l++)
{
    if (MyFiles.GetKey(l) == "file")
    {
        HttpPostedFile file = MyFiles.Get("file");
        // ...
    }
}

Upvotes: 0

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131423

You are checking the Form variables, where your code creates a blob that's send inside the HTTP request's body. The body isn't a form variable, it's simply the content inside an HTTP request that comes after the headers.

HttpRequest understands the contents of an HTTP request and exposes the various parts through its properties, eg Cookies, Files, Form, Headers.

If your code sends the binary data as a File, check the Files property. Otherwise, you can read the contents of the body using the InputStream property.

Assuming the data can be found in Files, the documentation of HttpPostedFile.InputStream describes how to read the file:

var files=Request.Files;
var aFile=files[0];

var length = aFile.ContentLength;
byte[] input = new byte[length];

aFile.InputStream.Read(input,0,length);

InputStream is just a stream so you can copy its contents in a buffer, write it out to disk etc

Upvotes: 2

Related Questions