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 开发者_Go百科file and a string in the same post?
I am using the WebClient
class.
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?
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.
You have to separate uploaded data with using boundaries. See this post for details.
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");
精彩评论