我需要将pdf文件和电话号码上传到将发送传真的服务。
有效的表单(来自网页)如下所示:
<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>问题是我需要从用C#编写的Windows应用程序中完成。
如何在同一篇文章中上传文件和字符串?
我正在使用WebClient类。 我尝试打开文件,读取其字节,并发布如下所示:
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);这不起作用。
我没有服务器日志或类似的东西来帮助我调试它。
我是否在WebClient类中遗漏了一些简单的内容? 是否还有其他方法可以将UploadFile和UploadData结合起来发布两个值,如网页(有效)吗?
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?
最满意答案
首先,在multipart / form-data标题中添加c.Headers.Add时会出现拼写错误。 :-)
其次,您需要通过在内容部分之间引入边界来正确格式化帖子。 看看这里 。
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.
更多推荐
发布评论