1

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?

juan
  • 80,295
  • 52
  • 162
  • 195

3 Answers3

3

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • Fixed the typo, it was only in the post, not in the code -- looking at boundaries now... – juan Nov 25 '10 at 14:10
2

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

Community
  • 1
  • 1
iburlakov
  • 4,164
  • 7
  • 38
  • 40
0

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");
David
  • 208,112
  • 36
  • 198
  • 279