2015-02-23 34 views
0

我试图将一个jpeg图片上传到PHP脚本。这是我的控制台应用程序program.csWebClient.UploadValues没有在c#中发布帖子请求

class Program 
{ 
    static void Main(string[] args) 
    { 
     Stopwatch stopWatch = new Stopwatch(); 
     stopWatch.Start(); 

     string result = UploadHandler.Post(
      "http://localhost/upload_test", 
      "frame.jpg" 
     ); 

     stopWatch.Stop(); 
     TimeSpan ts = stopWatch.Elapsed; 
     string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", 
      ts.Hours, ts.Minutes, ts.Seconds, 
      ts.Milliseconds/10); 

     Console.WriteLine("Result : {0}", result); 
     Console.WriteLine("File uploaded in : {0}", elapsedTime); 
     Console.ReadKey(); 
    } 
} 

这是我的UploadHandler类:

class UploadHandler 
{ 
    public static string Post(string serverUrl, string filePath) 
    { 
     string result = ""; 
     using (WebClient client = new WebClient()) 
     { 
      byte[] response = client.UploadValues(serverUrl, new NameValueCollection() 
      { 
       { "frameData", ToBase64(filePath) } 
      }); 
      result = Encoding.Default.GetString(response); 
     } 
     return result; 
    } 

    private static string ToBase64(string filePath) 
    { 
     return Convert.ToBase64String(
      File.ReadAllBytes(filePath) 
     ); 
    } 
} 

,这是我的PHP脚本接收上传:

<?php 

if (count($_POST) && isset($_POST['frameData'])) 
{ 
    file_put_contents('frame.jpg', base64_decode($_POST['frameData'])); 
    exit("OK"); 
} 
else 
{ 
    print_r($_POST); 
    exit("INVALID REQUEST"); 
} 

这是响应我获得:

enter image description here

任何想法,为什么这可能是?看来C#应用程序没有发出HTTP POST请求。

+0

尝试使用Fiddler之类的东西来查看您的请求。 – germi 2015-02-23 11:30:01

+0

我用'Wireshark'来监视所有的HTTP请求,并做了一个测试,我根本没有收到任何HTTP请求......这看起来很奇怪,因为我得到了回应。 – Latheesan 2015-02-23 11:32:57

+0

这种情况下的服务器与.Net应用程序在同一台机器上吗?在这种情况下,您需要通过计算机名称来寻址服务器,而不是'localhost',因为在处理'localhost'时.Net并不真正通过网络接口发送任何东西。见[这个问题](http://stackoverflow.com/questions/25836655/cant-see-webclient-post-request-in-fiddler)。 – germi 2015-02-23 12:37:44

回答

0

尝试:

client.UploadValues(serverUrl, "POST", new NameValueCollection() 
      { 
       { "frameData", ToBase64(filePath) } 
      }); 

编辑: 你应该调试这样的问题,与小提琴手:http://www.telerik.com/fiddler

首先确保你的C#应用​​程序在提琴手检查其发送的预期请求,然后你可以确保你的PHP应用程序在另一端做正确的事情。

现在你不会走得太远,因为目前还不清楚问题出在哪里。

+0

仍然不起作用。获取“INVALID REQUEST”。 – Latheesan 2015-02-23 11:41:47

+0

我编辑了我的评论,我认为你应该使用Fiddler并且能够快速识别问题。 – dustinmoris 2015-02-23 11:51:21

+0

在小提琴手上无所事事。 – Latheesan 2015-02-23 13:54:35

相关问题