将保存的图像和一些信息发送到服务器

时间:2015-04-24 18:25:03

标签: c# httpwebrequest httprequest httpwebresponse

我对此有一点问题,我可以向服务器发送多个信息串,但问题是图像......

这就是我所拥有的:

static void Main(string[] args)
    {


        string postDataFirst = "request=uploadPhoto&data[fileName]=photo&data[frameID]=2&photo=";
        string postDataSecond = "./hi.png";
        string postDataThird = "&requestID=2";

        string uri = "http://server1.libra.org/tlnet/Service/";


        HttpWebRequest request = (HttpWebRequest)
        WebRequest.Create(uri);
        request.KeepAlive = false;
        request.Method = "POST";

        byte[] postBytes1 = Encoding.ASCII.GetBytes(postDataFirst);
        byte[] postBytes2 = Encoding.ASCII.GetBytes(postDataSecond);
        byte[] postBytes3 = Encoding.ASCII.GetBytes(postDataThird);

        byte[] rv = new byte[postBytes1.Length + postBytes2.Length + postBytes3.Length];

        System.Buffer.BlockCopy(postBytes1, 0, rv, 0, postBytes1.Length);
        System.Buffer.BlockCopy(postBytes2, 0, rv, postBytes1.Length, postBytes2.Length);
        System.Buffer.BlockCopy(postBytes3, 0, rv, postBytes2.Length, postBytes3.Length);


        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = rv.Length;
        Stream requestStream = request.GetRequestStream();


        requestStream.Write(rv, 0, rv.Length);
        requestStream.Close();


        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
        Console.WriteLine(response.StatusCode);
    }

服务器在POST中获取值,我需要将它们传递给

"request"        = uploadPhoto,
"data[fileName]" = photo,   
"data[frameID]"  = randNum,
"photo"          = hi.png  (The file image)
"requestID"      = randNum

如果请求成功,则应返回类似

的内容
 "requestID": 1,
"data": {
    "qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZoAAAGaAQMAAAAMyBcgAAAABlBMVEX///8AAABVwtN+AAAAAXRSTlMAQObYZgAAAsZJREFUeJztmdut80AIhJFcQEpK6y4pBUTiHMMM4PyXAsjsg2Xv8u3TiMvYHOtt9nyZ+flwt2d8/j7cY88Oj4NcpwnaDJ12rUdF+QX9huIRUb+n8YglaDv0uG0PBaW0LgWljLAn6Hug0AjfUkZ2u1LQd0HYQb3JFBOZxF//lpGgfVAccAeZpFLMXUZ5h6DdEBZTx38eDBW0GuoVG5xSqCqLviPF87claB1EeSAgM8msLfF5HY44QZuhK2CIJ9QS9SYO5r3u8SZoN9TiyY+n08Qw4hhjXwjOewWthSAZu+NHJZHSFzMO7xK0FLIYPHoE6VJDErkn/S5P7QlaC2WAp81NjzPwsrUw0EacoP1QZY2RWKIX6ahroQZVDytoLeS31hMQHS1cZAfJLEmCFkP0ON17VLH+V4o9PrIuCVoOeYWWoK4OpCZYXMk2JDsWQVuhHDxOygNFp1qOqyftdEK3U9BmKFZ8jHY0Aw6no/Uu0ysqj6DFEFbWm0gdxgHFP6KOITdBuyEkjGpD0r9gt0EtuXd9ErQZKnmMicSM4ym8rTxoT1zQVgiZxFB0YGVGYnnN2273CloMzR1D1oBumGcwrWZwj6yCdkLoOg02Ra7znmLK1uqRVdBeKBJLqiUHlJpWH2/rPEMv9OhsJGgn1GUlBxT3z+YDGecxtSdoL9Qz6kgi+a+Uqnq2J+6zYxG0FrKaPqZ/8XiXtzV7EcpI0FLoZGcxmw+DfzFXJpZ4FbQeynY0iVYLZ9mSEUcVQauhz19hx5BRQLfJBSOroLVQL+LQEkJZflJQzp9ngtZC0Af/lXZFybJyJZt2vhwmuKDNUCqpWs/wKp590aurUU0zgnZDQyPu7V7BsPg4RWIR9B3Q6Ds849mL2B9Gp6AvgEDaeIOj5fUnNbKQoN0QSw3XMRqNeaWh6AhaDnUJcQoF7tVtVDGUn7hX0F7oB8KFqyvG2ESMAAAAAElFTkSuQmCC",
    "url": "http://server1.libra.org/tlnet/Service/uploaded/wfgfdgsdfdef-1429898987.4335.jpg",
    "filename": "wfgfdgsdfdef-1429898987.4335.jpg",
    "serverTime": 1429898987

但由于我无法发送图像,因此返回

{
"requestID": 1,
"data": {
    "serverTime": 1429899488
}

}

我唯一的问题是我无法将保存在我机器中的照片传递给服务器。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

几周前,我遇到了同样的障碍。而不是分享我的代码。我将与您分享您可以相应调整的参考资料。

http://blog.marcinbudny.com/2014/02/sending-binary-data-along-with-rest-api.html#.VTqNy5MkqYw

这篇文章一步步走完整个过程。您可以根据需要进行调整。

private static void SendImageSet(ImageSet imageSet)

{

var multipartContent = new MultipartFormDataContent();

var imageSetJson = JsonConvert.SerializeObject(imageSet, 
    new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    });

multipartContent.Add(
    new StringContent(imageSetJson, Encoding.UTF8, "application/json"), 
    "imageset"
    );

int counter = 0;
foreach (var image in imageSet.Images)
{
    var imageContent = new ByteArrayContent(image.ImageData);
    imageContent.Headers.ContentType = new MediaTypeHeaderValue(image.MimeType);
    multipartContent.Add(imageContent, "image" + counter++, image.FileName);
}

var response = new HttpClient()
    .PostAsync("http://localhost:53908/api/send", multipartContent)
    .Result;

var responseContent = response.Content.ReadAsStringAsync().Result;
Trace.Write(responseContent);

}

static void Main(string [] args) {

var imageSet = new ImageSet()
{
    Name = "Model",
    Images = Directory
        .EnumerateFiles("../../../../../SampleImages")
        .Where(file => new[] {".jpg", ".png"}.Contains(Path.GetExtension(file)))
        .Select(file => new Image
        {
            FileName = Path.GetFileName(file),
            MimeType = MimeMapping.GetMimeMapping(file),
            ImageData = File.ReadAllBytes(file)
        })
        .ToList()
};

SendImageSet(imageSet);

}