juan
juan

Reputation: 81902

How can I upload data and a file in the same post?

I need to upload a pdf file and a phone number to a service that will send a fax.

The form that works (from a webpage) looks like this:

<form action="send.php" method="post" enctype="multipart/form-data"> 
    <input type="file" name="pdf" id="pdf" /> 
    <input type="text" name="phonenumber" id="phonenumber" /> 
    <input type="submit" name="Submit" /> 
</form> 

The problem is that I need to do it from a windows application written in C#.

How can I upload both a file and a string in the same post?

I am using the WebClient class.
I tried opening the file, reading its bytes, and posting everything like this:

string content = "phonenumber="+request.PhoneNumber+"&pdf=";

WebClient c = new WebClient();
c.Headers.Add("Content-Type", "multipart/form-data");
c.Headers.Add("Cache-Control", "no-cache");
c.Headers.Add("Pragma", "no-cache");

byte[] bret = null;
byte[] p1 = Encoding.ASCII.GetBytes(content);
byte[] p2 = null;
using (StreamReader sr = new StreamReader(request.PdfPath))
{
    using (BinaryReader br = new BinaryReader(sr.BaseStream))
    {
        p2 = br.ReadBytes((int)sr.BaseStream.Length);
    }
}

byte[] all = new byte[p1.Length + p2.Length];
Array.Copy(p1, 0, all, 0, p1.Length);
Array.Copy(p2, 0, all, p1.Length, p2.Length);

bret = c.UploadData(url, "POST", all);

This does not work.

I do not have server logs or anything like that to help me debug it.

Am I missing something simple from the WebClient class? Is there any other way to combine UploadFile and UploadData to post both values like the webpage (that works) does?

Upvotes: 1

Views: 5619

Answers (3)

David
David

Reputation: 218857

This may or may not help, but I notice a typo:

c.Headers.Add("Content-Type", "multipart/form-dat");

should be

c.Headers.Add("Content-Type", "multipart/form-data");

Upvotes: 0

Jon
Jon

Reputation: 437386

First of all, you have a typo when doing c.Headers.Add in the multipart/form-data header. :-)

Second, you need to format your post correctly by introducing boundaries between the content parts. Take a look here.

Upvotes: 3

iburlakov
iburlakov

Reputation: 4232

You have to separate uploaded data with using boundaries. See this post for details.

Upvotes: 2

Related Questions