代码之家  ›  专栏  ›  技术社区  ›  juan

如何在同一个日志中上载数据和文件?

  •  1
  • juan  · 技术社区  · 14 年前

    我需要上传一个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);
    

    这不起作用。

    我没有服务器日志或类似的东西来帮助我调试它。

    我是不是错过了 网络客户端 上课?有别的方法可以合并吗 UploadFile UploadData 像网页一样发布这两个值吗?

    3 回复  |  直到 14 年前
        1
  •  3
  •   Jon    14 年前

    首先,你做错字 c.Headers.Add 在multipart/form数据头中。-)

    其次,您需要通过在内容部分之间引入边界来正确地格式化您的文章。看一看 here .

        2
  •  2
  •   Community Ramakrishna.p    7 年前

    你必须使用边界来分隔上传的数据。看看这个 post 有关详细信息。

        3
  •  0
  •   David    14 年前

    这可能有帮助,也可能没有帮助,但我注意到一个拼写错误:

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

    应该是

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